Best JavaScript code snippet using fast-check-monorepo
FramebufferSpec.js
Source:FramebufferSpec.js
1/*global defineSuite*/2defineSuite([3 'Renderer/Framebuffer',4 'Core/Color',5 'Core/PixelFormat',6 'Core/PrimitiveType',7 'Core/WebGLConstants',8 'Renderer/Buffer',9 'Renderer/BufferUsage',10 'Renderer/ClearCommand',11 'Renderer/ContextLimits',12 'Renderer/CubeMap',13 'Renderer/DrawCommand',14 'Renderer/PixelDatatype',15 'Renderer/Renderbuffer',16 'Renderer/RenderbufferFormat',17 'Renderer/RenderState',18 'Renderer/ShaderProgram',19 'Renderer/Texture',20 'Renderer/VertexArray',21 'Specs/createContext'22 ], function(23 Framebuffer,24 Color,25 PixelFormat,26 PrimitiveType,27 WebGLConstants,28 Buffer,29 BufferUsage,30 ClearCommand,31 ContextLimits,32 CubeMap,33 DrawCommand,34 PixelDatatype,35 Renderbuffer,36 RenderbufferFormat,37 RenderState,38 ShaderProgram,39 Texture,40 VertexArray,41 createContext) {42 'use strict';43 var context;44 var sp;45 var va;46 var framebuffer;47 beforeAll(function() {48 context = createContext();49 });50 afterAll(function() {51 context.destroyForSpecs();52 });53 afterEach(function() {54 sp = sp && sp.destroy();55 va = va && va.destroy();56 framebuffer = framebuffer && framebuffer.destroy();57 });58 it('has a color texture attachment', function() {59 framebuffer = new Framebuffer({60 context : context,61 colorTextures : [new Texture({62 context : context,63 width : 1,64 height : 165 })]66 });67 expect(framebuffer.getColorTexture(0)).toBeDefined();68 });69 it('has a color renderbuffer attachment', function() {70 framebuffer = new Framebuffer({71 context : context,72 colorRenderbuffers : [new Renderbuffer({73 context : context,74 format : RenderbufferFormat.RGBA475 })]76 });77 expect(framebuffer.getColorRenderbuffer(0)).toBeDefined();78 });79 it('has a depth texture attachment', function() {80 if (context.depthTexture) {81 framebuffer = new Framebuffer({82 context : context,83 depthTexture : new Texture({84 context : context,85 width : 1,86 height : 1,87 pixelFormat : PixelFormat.DEPTH_COMPONENT,88 pixelDatatype : PixelDatatype.UNSIGNED_SHORT89 })90 });91 expect(framebuffer.depthTexture).toBeDefined();92 }93 });94 it('has a depth renderbuffer attachment', function() {95 framebuffer = new Framebuffer({96 context : context,97 depthRenderbuffer : new Renderbuffer({98 context : context,99 format : RenderbufferFormat.DEPTH_COMPONENT16100 })101 });102 expect(framebuffer.depthRenderbuffer).toBeDefined();103 });104 it('has a stencil renderbuffer attachment', function() {105 framebuffer = new Framebuffer({106 context : context,107 stencilRenderbuffer : new Renderbuffer({108 context : context,109 format : RenderbufferFormat.STENCIL_INDEX8110 })111 });112 expect(framebuffer.stencilRenderbuffer).toBeDefined();113 });114 it('has a depth-stencil texture attachment', function() {115 if (context.depthTexture) {116 framebuffer = new Framebuffer({117 context : context,118 depthStencilTexture : new Texture({119 context : context,120 width : 1,121 height : 1,122 pixelFormat : PixelFormat.DEPTH_STENCIL,123 pixelDatatype : PixelDatatype.UNSIGNED_INT_24_8124 })125 });126 expect(framebuffer.depthStencilTexture).toBeDefined();127 }128 });129 it('has a depth-stencil renderbuffer attachment', function() {130 framebuffer = new Framebuffer({131 context : context,132 depthStencilRenderbuffer : new Renderbuffer({133 context : context,134 format : RenderbufferFormat.DEPTH_STENCIL135 })136 });137 expect(framebuffer.depthStencilRenderbuffer).toBeDefined();138 });139 it('has a depth attachment', function() {140 framebuffer = new Framebuffer({141 context : context142 });143 expect(framebuffer.hasDepthAttachment).toEqual(false);144 framebuffer.destroy();145 framebuffer = new Framebuffer({146 context : context,147 depthRenderbuffer : new Renderbuffer({148 context : context,149 format : RenderbufferFormat.DEPTH_COMPONENT16150 })151 });152 expect(framebuffer.hasDepthAttachment).toEqual(true);153 });154 it('clears a color attachment', function() {155 // 1 of 3. Clear default color buffer to black.156 ClearCommand.ALL.execute(context);157 expect(context).toReadPixels([0, 0, 0, 255]);158 // 2 of 3. Clear framebuffer color attachment to green.159 var colorTexture = new Texture({160 context : context,161 width : 1,162 height : 1163 });164 framebuffer = new Framebuffer({165 context : context,166 colorTextures : [colorTexture]167 });168 var clearCommand = new ClearCommand({169 color : new Color (0.0, 1.0, 0.0, 1.0),170 framebuffer : framebuffer171 });172 clearCommand.execute(context);173 // 3 of 3. Render green to default color buffer by reading from previous color attachment174 var fs = 'uniform sampler2D u_texture; void main() { gl_FragColor = texture2D(u_texture, vec2(0.0)); }';175 var uniformMap = {176 u_texture : function() {177 return colorTexture;178 }179 };180 expect({181 context : context,182 fragmentShader : fs,183 uniformMap : uniformMap184 }).contextToRender([0, 255, 0, 255]);185 });186 it('clears a cube map face color attachment', function() {187 var cubeMap = new CubeMap({188 context : context,189 width : 1,190 height : 1191 });192 // 1 of 3. Clear default color buffer to black.193 ClearCommand.ALL.execute(context);194 expect(context).toReadPixels([0, 0, 0, 255]);195 // 2 of 3. Clear framebuffer color attachment to green.196 framebuffer = new Framebuffer({197 context : context,198 colorTextures : [cubeMap.positiveX],199 destroyAttachments : false200 });201 var clearCommand = new ClearCommand({202 color : new Color (0.0, 1.0, 0.0, 1.0),203 framebuffer : framebuffer204 });205 clearCommand.execute(context);206 // 3 of 3. Render green to default color buffer by reading from previous color attachment207 var fs = 'uniform samplerCube u_cubeMap; void main() { gl_FragColor = textureCube(u_cubeMap, vec3(1.0, 0.0, 0.0)); }';208 var uniformMap = {209 u_cubeMap : function() {210 return cubeMap;211 }212 };213 expect({214 context : context,215 fragmentShader : fs,216 uniformMap : uniformMap217 }).contextToRender([0, 255, 0, 255]);218 cubeMap = cubeMap.destroy();219 });220 it('draws to a color attachment', function() {221 var colorTexture = new Texture({222 context : context,223 width : 1,224 height : 1225 });226 framebuffer = new Framebuffer({227 context : context,228 colorTextures : [colorTexture]229 });230 // 1 of 4. Clear default color buffer to black.231 ClearCommand.ALL.execute(context);232 expect(context).toReadPixels([0, 0, 0, 255]);233 // 2 of 4. Render green point into color attachment.234 var vs = 'attribute vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }';235 var fs = 'void main() { gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0); }';236 sp = ShaderProgram.fromCache({237 context : context,238 vertexShaderSource : vs,239 fragmentShaderSource : fs,240 attributeLocations : {241 position : 0242 }243 });244 va = new VertexArray({245 context : context,246 attributes : [{247 index : 0,248 vertexBuffer : Buffer.createVertexBuffer({249 context : context,250 typedArray : new Float32Array([0, 0, 0, 1]),251 usage : BufferUsage.STATIC_DRAW252 }),253 componentsPerAttribute : 4254 }]255 });256 var command = new DrawCommand({257 primitiveType : PrimitiveType.POINTS,258 shaderProgram : sp,259 vertexArray : va,260 framebuffer : framebuffer261 });262 command.execute(context);263 // 3 of 4. Verify default color buffer is still black.264 expect(context).toReadPixels([0, 0, 0, 255]);265 // 4 of 4. Render green to default color buffer by reading from previous color attachment266 var fs2 = 'uniform sampler2D u_texture; void main() { gl_FragColor = texture2D(u_texture, vec2(0.0)); }';267 var uniformMap = {268 u_texture : function() {269 return colorTexture;270 }271 };272 expect({273 context : context,274 fragmentShader : fs2,275 uniformMap : uniformMap276 }).contextToRender([0, 255, 0, 255]);277 });278 function renderDepthAttachment(framebuffer, texture) {279 ClearCommand.ALL.execute(context);280 // 1 of 3. Render green point into color attachment.281 var vs = 'attribute vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }';282 var fs = 'void main() { gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0); }';283 sp = ShaderProgram.fromCache({284 context : context,285 vertexShaderSource : vs,286 fragmentShaderSource : fs,287 attributeLocations : {288 position : 0289 }290 });291 va = new VertexArray({292 context : context,293 attributes : [{294 index : 0,295 vertexBuffer : Buffer.createVertexBuffer({296 context : context,297 typedArray : new Float32Array([0, 0, 0, 1]),298 usage : BufferUsage.STATIC_DRAW299 }),300 componentsPerAttribute : 4301 }]302 });303 var command = new DrawCommand({304 primitiveType : PrimitiveType.POINTS,305 shaderProgram : sp,306 vertexArray : va,307 framebuffer : framebuffer,308 renderState : RenderState.fromCache({309 depthTest : {310 enabled : true311 }312 })313 });314 command.execute(context);315 // 2 of 3. Verify default color buffer is still black.316 expect(context).toReadPixels([0, 0, 0, 255]);317 // 3 of 3. Render green to default color buffer by reading from previous color attachment318 var vs2 = 'attribute vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }';319 var fs2 = 'uniform sampler2D u_texture; void main() { gl_FragColor = texture2D(u_texture, vec2(0.0)).rrrr; }';320 var sp2 = ShaderProgram.fromCache({321 context : context,322 vertexShaderSource : vs2,323 fragmentShaderSource : fs2,324 attributeLocations : {325 position : 0326 }327 });328 var uniformMap = {329 u_texture : function() {330 return texture;331 }332 };333 command = new DrawCommand({334 primitiveType : PrimitiveType.POINTS,335 shaderProgram : sp2,336 vertexArray : va,337 uniformMap : uniformMap338 });339 command.execute(context);340 sp2 = sp2.destroy();341 return context.readPixels();342 }343 it('draws to a depth texture attachment', function() {344 if (context.depthTexture) {345 framebuffer = new Framebuffer({346 context : context,347 colorTextures : [new Texture({348 context : context,349 width : 1,350 height : 1351 })],352 depthTexture : new Texture({353 context : context,354 width : 1,355 height : 1,356 pixelFormat : PixelFormat.DEPTH_COMPONENT,357 pixelDatatype : PixelDatatype.UNSIGNED_SHORT358 })359 });360 if (framebuffer.status === WebGLConstants.FRAMEBUFFER_COMPLETE) {361 expect(renderDepthAttachment(framebuffer, framebuffer.depthTexture)).toEqualEpsilon([128, 128, 128, 255], 1);362 }363 }364 });365 it('draws to a depth-stencil texture attachment', function() {366 if (context.depthTexture) {367 framebuffer = new Framebuffer({368 context : context,369 colorTextures : [new Texture({370 context : context,371 width : 1,372 height : 1373 })],374 depthStencilTexture : new Texture({375 context : context,376 width : 1,377 height : 1,378 pixelFormat : PixelFormat.DEPTH_STENCIL,379 pixelDatatype : PixelDatatype.UNSIGNED_INT_24_8380 })381 });382 if (framebuffer.status === WebGLConstants.FRAMEBUFFER_COMPLETE) {383 expect(renderDepthAttachment(framebuffer, framebuffer.depthStencilTexture)).toEqualEpsilon([128, 128, 128, 255], 1);384 }385 }386 });387 it('draws with a depth attachment', function() {388 framebuffer = new Framebuffer({389 context : context,390 colorTextures : [new Texture({391 context : context,392 width : 1,393 height : 1394 })],395 depthRenderbuffer : new Renderbuffer({396 context : context,397 format : RenderbufferFormat.DEPTH_COMPONENT16,398 width : 1,399 height : 1400 })401 });402 var vs = 'attribute vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }';403 var fs = 'void main() { gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0); }';404 sp = ShaderProgram.fromCache({405 context : context,406 vertexShaderSource : vs,407 fragmentShaderSource : fs,408 attributeLocations : {409 position : 0410 }411 });412 va = new VertexArray({413 context : context,414 attributes : [{415 index : 0,416 vertexBuffer : Buffer.createVertexBuffer({417 context : context,418 typedArray : new Float32Array([0, 0, 0, 1]),419 usage : BufferUsage.STATIC_DRAW420 }),421 componentsPerAttribute : 4422 }]423 });424 // 1 of 3. Clear framebuffer425 var clearCommand = new ClearCommand({426 color : new Color(0.0, 0.0, 0.0, 0.0),427 depth : 1.0,428 framebuffer : framebuffer429 });430 clearCommand.execute(context);431 expect({432 context : context,433 framebuffer : framebuffer434 }).toReadPixels([0, 0, 0, 0]);435 // 2 of 3. Does not pass depth test436 var command = new DrawCommand({437 primitiveType : PrimitiveType.POINTS,438 shaderProgram : sp,439 vertexArray : va,440 framebuffer : framebuffer,441 renderState : RenderState.fromCache({442 depthTest : {443 enabled : true,444 func : WebGLConstants.NEVER445 }446 })447 });448 command.execute(context);449 expect({450 context : context,451 framebuffer : framebuffer452 }).toReadPixels([0, 0, 0, 0]);453 // 3 of 3. Passes depth test454 command = new DrawCommand({455 primitiveType : PrimitiveType.POINTS,456 shaderProgram : sp,457 vertexArray : va,458 framebuffer : framebuffer,459 renderState : RenderState.fromCache({460 depthTest : {461 enabled : true,462 func : WebGLConstants.ALWAYS463 }464 })465 });466 command.execute(context);467 expect({468 context : context,469 framebuffer : framebuffer470 }).toReadPixels([255, 255, 255, 255]);471 });472 it('draws with multiple render targets', function() {473 if (!context.drawBuffers) {474 return;475 }476 var source = new Uint8Array(4);477 var colorTexture0 = new Texture({478 context : context,479 source : {480 arrayBufferView : source,481 width : 1,482 height : 1483 }484 });485 var colorTexture1 = new Texture({486 context : context,487 source : {488 arrayBufferView : source,489 width : 1,490 height : 1491 }492 });493 framebuffer = new Framebuffer({494 context : context,495 colorTextures : [colorTexture0, colorTexture1]496 });497 // 1 of 5. Clear default color buffer to black.498 ClearCommand.ALL.execute(context);499 expect(context).toReadPixels([0, 0, 0, 255]);500 // 2 of 5. Render red point into color attachment 0 and green point to color attachment 1.501 var vs = 'attribute vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }';502 var fs = '#extension GL_EXT_draw_buffers : enable \n void main() { gl_FragData[0] = vec4(1.0, 0.0, 0.0, 1.0); gl_FragData[1] = vec4(0.0, 1.0, 0.0, 1.0); }';503 sp = ShaderProgram.fromCache({504 context : context,505 vertexShaderSource : vs,506 fragmentShaderSource : fs,507 attributeLocations : {508 position : 0509 }510 });511 va = new VertexArray({512 context : context,513 attributes : [{514 index : 0,515 vertexBuffer : Buffer.createVertexBuffer({516 context : context,517 typedArray : new Float32Array([0, 0, 0, 1]),518 usage : BufferUsage.STATIC_DRAW519 }),520 componentsPerAttribute : 4521 }]522 });523 var command = new DrawCommand({524 primitiveType : PrimitiveType.POINTS,525 shaderProgram : sp,526 vertexArray : va,527 framebuffer : framebuffer528 });529 command.execute(context);530 // 3 of 5. Verify default color buffer is still black.531 expect(context).toReadPixels([0, 0, 0, 255]);532 // 4 of 5. Render yellow to default color buffer by reading from previous color attachments533 var vs2 = 'attribute vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }';534 var fs2 = 'uniform sampler2D u_texture0; uniform sampler2D u_texture1; void main() { gl_FragColor = texture2D(u_texture0, vec2(0.0)) + texture2D(u_texture1, vec2(0.0)); }';535 var sp2 = ShaderProgram.fromCache({536 context : context,537 vertexShaderSource : vs2,538 fragmentShaderSource : fs2,539 attributeLocations : {540 position : 0541 }542 });543 var uniformMap = {544 u_texture0 : function() {545 return colorTexture0;546 },547 u_texture1 : function() {548 return colorTexture1;549 }550 };551 command = new DrawCommand({552 primitiveType : PrimitiveType.POINTS,553 shaderProgram : sp2,554 vertexArray : va,555 uniformMap : uniformMap556 });557 command.execute(context);558 expect(context).toReadPixels([255, 255, 0, 255]);559 // 5 of 5. Verify clearing multiple color attachments560 var clearCommand = new ClearCommand({561 color : new Color (0.0, 0.0, 0.0, 0.0),562 framebuffer : framebuffer563 });564 clearCommand.execute(context);565 command = new DrawCommand({566 primitiveType : PrimitiveType.POINTS,567 shaderProgram : sp2,568 vertexArray : va569 });570 command.execute(context);571 expect(context).toReadPixels([0, 0, 0, 255]);572 sp2 = sp2.destroy();573 });574 it('gets the status of a complete framebuffer', function() {575 framebuffer = new Framebuffer({576 context : context,577 colorTextures : [new Texture({578 context : context,579 width : 1,580 height : 1581 })],582 depthRenderbuffer : new Renderbuffer({583 context : context,584 format : RenderbufferFormat.DEPTH_COMPONENT16,585 width : 1,586 height : 1587 })588 });589 expect(framebuffer.status).toEqual(WebGLConstants.FRAMEBUFFER_COMPLETE);590 });591 it('gets the status of a incomplete framebuffer', function() {592 if (!!window.webglStub) {593 return;594 }595 framebuffer = new Framebuffer({596 context : context,597 colorTextures : [new Texture({598 context : context,599 width : 1,600 height : 1601 })],602 depthRenderbuffer : new Renderbuffer({603 context : context,604 format : RenderbufferFormat.RGBA4,605 width : 2,606 height : 2607 })608 });609 expect(framebuffer.status).not.toEqual(WebGLConstants.FRAMEBUFFER_COMPLETE);610 });611 it('destroys', function() {612 var f = new Framebuffer({613 context : context614 });615 expect(f.isDestroyed()).toEqual(false);616 f.destroy();617 expect(f.isDestroyed()).toEqual(true);618 });619 it('throws when created with color texture and color renderbuffer attachments', function() {620 expect(function() {621 framebuffer = new Framebuffer({622 context : context,623 colorTextures : 'not undefined',624 colorRenderbuffers : 'not undefined'625 });626 }).toThrowDeveloperError();627 });628 it('throws when created with depth texture and depth renderbuffer attachments', function() {629 expect(function() {630 framebuffer = new Framebuffer({631 context : context,632 depthTexture : 'not undefined',633 depthRenderbuffer : 'not undefined'634 });635 }).toThrowDeveloperError();636 });637 it('throws when created with depth-stencil texture and depth-stencil renderbuffer attachments', function() {638 expect(function() {639 framebuffer = new Framebuffer({640 context : context,641 depthStencilTexture : 'not undefined',642 depthStencilRenderbuffer : 'not undefined'643 });644 }).toThrowDeveloperError();645 });646 it('throws when created with depth and depth-stencil attachments', function() {647 expect(function() {648 framebuffer = new Framebuffer({649 context : context,650 depthRenderbuffer : 'not undefined',651 depthStencilRenderbuffer : 'not undefined'652 });653 }).toThrowDeveloperError();654 });655 it('throws when created with stencil and depth-stencil attachments', function() {656 expect(function() {657 framebuffer = new Framebuffer({658 context : context,659 stencilRenderbuffer : 'not undefined',660 depthStencilRenderbuffer : 'not undefined'661 });662 }).toThrowDeveloperError();663 });664 it('throws when created with depth and stencil attachments', function() {665 expect(function() {666 framebuffer = new Framebuffer({667 context : context,668 depthRenderbuffer : 'not undefined',669 stencilRenderbuffer : 'not undefined'670 });671 }).toThrowDeveloperError();672 });673 it('throws when created with a color texture with a non-color pixel format', function() {674 if (context.depthTexture) {675 expect(function() {676 framebuffer = new Framebuffer({677 context : context,678 colorTextures : [new Texture({679 context : context,680 width : 1,681 height : 1,682 pixelFormat : PixelFormat.DEPTH_COMPONENT,683 pixelDatatype : PixelDatatype.UNSIGNED_SHORT684 })]685 });686 }).toThrowDeveloperError();687 }688 });689 it('throws when created with a depth texture without a DEPTH_COMPONENT pixel format', function() {690 expect(function() {691 framebuffer = new Framebuffer({692 context : context,693 depthTexture : new Texture({694 context : context,695 width : 1,696 height : 1697 })698 });699 }).toThrowDeveloperError();700 });701 it('throws when created with a depth-stencil texture without a DEPTH_STENCIL pixel format', function() {702 expect(function() {703 framebuffer = new Framebuffer({704 context : context,705 depthStencilTexture : new Texture({706 context : context,707 width : 1,708 height : 1709 })710 });711 }).toThrowDeveloperError();712 });713 it('throws when the depth test is enabled without an appropriate attachment', function() {714 framebuffer = new Framebuffer({715 context : context,716 colorTextures : [new Texture({717 context : context,718 width : 1,719 height : 1720 })]721 });722 var vs = 'attribute vec4 position; void main() { gl_PointSize = 1.0; gl_Position = position; }';723 var fs = 'void main() { gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0); }';724 sp = ShaderProgram.fromCache({725 context : context,726 vertexShaderSource : vs,727 fragmentShaderSource : fs,728 attributeLocations : {729 position : 0730 }731 });732 va = new VertexArray({733 context : context,734 attributes : [{735 index : 0,736 vertexBuffer : Buffer.createVertexBuffer({737 context : context,738 typedArray : new Float32Array([0, 0, 0, 1]),739 usage : BufferUsage.STATIC_DRAW740 }),741 componentsPerAttribute : 4742 }]743 });744 expect(function() {745 var command = new DrawCommand({746 primitiveType : PrimitiveType.POINTS,747 shaderProgram : sp,748 vertexArray : va,749 framebuffer : framebuffer,750 renderState : RenderState.fromCache({751 depthTest : {752 enabled : true753 }754 })755 });756 command.execute(context);757 }).toThrowDeveloperError();758 });759 it('throws when the number of color texture exceeds the number color attachments supported', function() {760 expect(function() {761 return new Framebuffer({762 context : context,763 colorTextures : new Array(ContextLimits.maximumColorAttachments + 1)764 });765 }).toThrowDeveloperError();766 });767 it('throws when the number of color renderbuffers exceeds the number color attachments supported', function() {768 expect(function() {769 return new Framebuffer({770 context : context,771 colorRenderbuffers : new Array(ContextLimits.maximumColorAttachments + 1)772 });773 }).toThrowDeveloperError();774 });775 it('throws when the index to getColorTexture is out of bounds', function(){776 framebuffer = new Framebuffer({777 context : context778 });779 expect(function() {780 framebuffer.getColorTexture();781 }).toThrowDeveloperError();782 expect(function() {783 framebuffer.getColorTexture(-1);784 }).toThrowDeveloperError();785 expect(function() {786 framebuffer.getColorTexture(ContextLimits.maximumColorAttachments + 1);787 }).toThrowDeveloperError();788 });789 it('throws when the index to getColorRenderbuffer is out of bounds', function(){790 framebuffer = new Framebuffer({791 context : context792 });793 expect(function() {794 framebuffer.getColorRenderbuffer();795 }).toThrowDeveloperError();796 expect(function() {797 framebuffer.getColorRenderbuffer(-1);798 }).toThrowDeveloperError();799 expect(function() {800 framebuffer.getColorRenderbuffer(ContextLimits.maximumColorAttachments + 1);801 }).toThrowDeveloperError();802 });803 it('fails to destroy', function() {804 var f = new Framebuffer({805 context : context806 });807 f.destroy();808 expect(function() {809 f.destroy();810 }).toThrowDeveloperError();811 });812 it('throws when there is no context', function() {813 expect(function() {814 return new Framebuffer();815 }).toThrowDeveloperError();816 });...
parser.js
Source:parser.js
1"use strict";2Object.defineProperty(exports, "__esModule", { value: true });3/**4 * @license5 * Copyright Google Inc. All Rights Reserved.6 *7 * Use of this source code is governed by an MIT-style license that can be8 * found in the LICENSE file at https://angular.io/license9 */10const exception_1 = require("../exception");11class JsonException extends exception_1.BaseException {12}13exports.JsonException = JsonException;14/**15 * A character was invalid in this context.16 */17class InvalidJsonCharacterException extends JsonException {18 constructor(context) {19 const pos = context.previous;20 const invalidChar = JSON.stringify(_peek(context));21 super(`Invalid JSON character: ${invalidChar} at ${pos.line}:${pos.character}.`);22 this.invalidChar = invalidChar;23 this.line = pos.line;24 this.offset = pos.offset;25 this.character = pos.character;26 }27}28exports.InvalidJsonCharacterException = InvalidJsonCharacterException;29/**30 * More input was expected, but we reached the end of the stream.31 */32class UnexpectedEndOfInputException extends JsonException {33 constructor(_context) {34 super(`Unexpected end of file.`);35 }36}37exports.UnexpectedEndOfInputException = UnexpectedEndOfInputException;38/**39 * An error happened within a file.40 */41class PathSpecificJsonException extends JsonException {42 constructor(path, exception) {43 super(`An error happened at file path ${JSON.stringify(path)}: ${exception.message}`);44 this.path = path;45 this.exception = exception;46 }47}48exports.PathSpecificJsonException = PathSpecificJsonException;49/**50 * Peek and return the next character from the context.51 * @private52 */53function _peek(context) {54 return context.original[context.position.offset];55}56/**57 * Move the context to the next character, including incrementing the line if necessary.58 * @private59 */60function _next(context) {61 context.previous = context.position;62 let { offset, line, character } = context.position;63 const char = context.original[offset];64 offset++;65 if (char == '\n') {66 line++;67 character = 0;68 }69 else {70 character++;71 }72 context.position = { offset, line, character };73}74function _token(context, valid) {75 const char = _peek(context);76 if (valid) {77 if (!char) {78 throw new UnexpectedEndOfInputException(context);79 }80 if (valid.indexOf(char) == -1) {81 throw new InvalidJsonCharacterException(context);82 }83 }84 // Move the position of the context to the next character.85 _next(context);86 return char;87}88/**89 * Read the exponent part of a number. The exponent part is looser for JSON than the number90 * part. `str` is the string of the number itself found so far, and start the position91 * where the full number started. Returns the node found.92 * @private93 */94function _readExpNumber(context, start, str, comments) {95 let char;96 let signed = false;97 while (true) {98 char = _token(context);99 if (char == '+' || char == '-') {100 if (signed) {101 break;102 }103 signed = true;104 str += char;105 }106 else if (char == '0' || char == '1' || char == '2' || char == '3' || char == '4'107 || char == '5' || char == '6' || char == '7' || char == '8' || char == '9') {108 signed = true;109 str += char;110 }111 else {112 break;113 }114 }115 // We're done reading this number.116 context.position = context.previous;117 return {118 kind: 'number',119 start,120 end: context.position,121 text: context.original.substring(start.offset, context.position.offset),122 value: Number.parseFloat(str),123 comments: comments,124 };125}126/**127 * Read the hexa part of a 0xBADCAFE hexadecimal number.128 * @private129 */130function _readHexaNumber(context, isNegative, start, comments) {131 // Read an hexadecimal number, until it's not hexadecimal.132 let hexa = '';133 const valid = '0123456789abcdefABCDEF';134 for (let ch = _peek(context); ch && valid.includes(ch); ch = _peek(context)) {135 // Add it to the hexa string.136 hexa += ch;137 // Move the position of the context to the next character.138 _next(context);139 }140 const value = Number.parseInt(hexa, 16);141 // We're done reading this number.142 return {143 kind: 'number',144 start,145 end: context.position,146 text: context.original.substring(start.offset, context.position.offset),147 value: isNegative ? -value : value,148 comments,149 };150}151/**152 * Read a number from the context.153 * @private154 */155function _readNumber(context, comments = _readBlanks(context)) {156 let str = '';157 let dotted = false;158 const start = context.position;159 // read until `e` or end of line.160 while (true) {161 const char = _token(context);162 // Read tokens, one by one.163 if (char == '-') {164 if (str != '') {165 throw new InvalidJsonCharacterException(context);166 }167 }168 else if (char == 'I'169 && (str == '-' || str == '' || str == '+')170 && (context.mode & JsonParseMode.NumberConstantsAllowed) != 0) {171 // Infinity?172 // _token(context, 'I'); Already read.173 _token(context, 'n');174 _token(context, 'f');175 _token(context, 'i');176 _token(context, 'n');177 _token(context, 'i');178 _token(context, 't');179 _token(context, 'y');180 str += 'Infinity';181 break;182 }183 else if (char == '0') {184 if (str == '0' || str == '-0') {185 throw new InvalidJsonCharacterException(context);186 }187 }188 else if (char == '1' || char == '2' || char == '3' || char == '4' || char == '5'189 || char == '6' || char == '7' || char == '8' || char == '9') {190 if (str == '0' || str == '-0') {191 throw new InvalidJsonCharacterException(context);192 }193 }194 else if (char == '+' && str == '') {195 // Pass over.196 }197 else if (char == '.') {198 if (dotted) {199 throw new InvalidJsonCharacterException(context);200 }201 dotted = true;202 }203 else if (char == 'e' || char == 'E') {204 return _readExpNumber(context, start, str + char, comments);205 }206 else if (char == 'x' && (str == '0' || str == '-0')207 && (context.mode & JsonParseMode.HexadecimalNumberAllowed) != 0) {208 return _readHexaNumber(context, str == '-0', start, comments);209 }210 else {211 // We read one too many characters, so rollback the last character.212 context.position = context.previous;213 break;214 }215 str += char;216 }217 // We're done reading this number.218 if (str.endsWith('.') && (context.mode & JsonParseMode.HexadecimalNumberAllowed) == 0) {219 throw new InvalidJsonCharacterException(context);220 }221 return {222 kind: 'number',223 start,224 end: context.position,225 text: context.original.substring(start.offset, context.position.offset),226 value: Number.parseFloat(str),227 comments,228 };229}230/**231 * Read a string from the context. Takes the comments of the string or read the blanks before the232 * string.233 * @private234 */235function _readString(context, comments = _readBlanks(context)) {236 const start = context.position;237 // Consume the first string delimiter.238 const delim = _token(context);239 if ((context.mode & JsonParseMode.SingleQuotesAllowed) == 0) {240 if (delim == '\'') {241 throw new InvalidJsonCharacterException(context);242 }243 }244 let str = '';245 while (true) {246 let char = _token(context);247 if (char == delim) {248 return {249 kind: 'string',250 start,251 end: context.position,252 text: context.original.substring(start.offset, context.position.offset),253 value: str,254 comments: comments,255 };256 }257 else if (char == '\\') {258 char = _token(context);259 switch (char) {260 case '\\':261 case '\/':262 case '"':263 case delim:264 str += char;265 break;266 case 'b':267 str += '\b';268 break;269 case 'f':270 str += '\f';271 break;272 case 'n':273 str += '\n';274 break;275 case 'r':276 str += '\r';277 break;278 case 't':279 str += '\t';280 break;281 case 'u':282 const [c0] = _token(context, '0123456789abcdefABCDEF');283 const [c1] = _token(context, '0123456789abcdefABCDEF');284 const [c2] = _token(context, '0123456789abcdefABCDEF');285 const [c3] = _token(context, '0123456789abcdefABCDEF');286 str += String.fromCharCode(parseInt(c0 + c1 + c2 + c3, 16));287 break;288 case undefined:289 throw new UnexpectedEndOfInputException(context);290 case '\n':291 // Only valid when multiline strings are allowed.292 if ((context.mode & JsonParseMode.MultiLineStringAllowed) == 0) {293 throw new InvalidJsonCharacterException(context);294 }295 str += char;296 break;297 default:298 throw new InvalidJsonCharacterException(context);299 }300 }301 else if (char === undefined) {302 throw new UnexpectedEndOfInputException(context);303 }304 else if (char == '\b' || char == '\f' || char == '\n' || char == '\r' || char == '\t') {305 throw new InvalidJsonCharacterException(context);306 }307 else {308 str += char;309 }310 }311}312/**313 * Read the constant `true` from the context.314 * @private315 */316function _readTrue(context, comments = _readBlanks(context)) {317 const start = context.position;318 _token(context, 't');319 _token(context, 'r');320 _token(context, 'u');321 _token(context, 'e');322 const end = context.position;323 return {324 kind: 'true',325 start,326 end,327 text: context.original.substring(start.offset, end.offset),328 value: true,329 comments,330 };331}332/**333 * Read the constant `false` from the context.334 * @private335 */336function _readFalse(context, comments = _readBlanks(context)) {337 const start = context.position;338 _token(context, 'f');339 _token(context, 'a');340 _token(context, 'l');341 _token(context, 's');342 _token(context, 'e');343 const end = context.position;344 return {345 kind: 'false',346 start,347 end,348 text: context.original.substring(start.offset, end.offset),349 value: false,350 comments,351 };352}353/**354 * Read the constant `null` from the context.355 * @private356 */357function _readNull(context, comments = _readBlanks(context)) {358 const start = context.position;359 _token(context, 'n');360 _token(context, 'u');361 _token(context, 'l');362 _token(context, 'l');363 const end = context.position;364 return {365 kind: 'null',366 start,367 end,368 text: context.original.substring(start.offset, end.offset),369 value: null,370 comments: comments,371 };372}373/**374 * Read the constant `NaN` from the context.375 * @private376 */377function _readNaN(context, comments = _readBlanks(context)) {378 const start = context.position;379 _token(context, 'N');380 _token(context, 'a');381 _token(context, 'N');382 const end = context.position;383 return {384 kind: 'number',385 start,386 end,387 text: context.original.substring(start.offset, end.offset),388 value: NaN,389 comments: comments,390 };391}392/**393 * Read an array of JSON values from the context.394 * @private395 */396function _readArray(context, comments = _readBlanks(context)) {397 const start = context.position;398 // Consume the first delimiter.399 _token(context, '[');400 const value = [];401 const elements = [];402 _readBlanks(context);403 if (_peek(context) != ']') {404 const node = _readValue(context);405 elements.push(node);406 value.push(node.value);407 }408 while (_peek(context) != ']') {409 _token(context, ',');410 const valueComments = _readBlanks(context);411 if ((context.mode & JsonParseMode.TrailingCommasAllowed) !== 0 && _peek(context) === ']') {412 break;413 }414 const node = _readValue(context, valueComments);415 elements.push(node);416 value.push(node.value);417 }418 _token(context, ']');419 return {420 kind: 'array',421 start,422 end: context.position,423 text: context.original.substring(start.offset, context.position.offset),424 value,425 elements,426 comments,427 };428}429/**430 * Read an identifier from the context. An identifier is a valid JavaScript identifier, and this431 * function is only used in Loose mode.432 * @private433 */434function _readIdentifier(context, comments = _readBlanks(context)) {435 const start = context.position;436 let char = _peek(context);437 if (char && '0123456789'.indexOf(char) != -1) {438 const identifierNode = _readNumber(context);439 return {440 kind: 'identifier',441 start,442 end: identifierNode.end,443 text: identifierNode.text,444 value: identifierNode.value.toString(),445 };446 }447 const identValidFirstChar = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMOPQRSTUVWXYZ';448 const identValidChar = '_$abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMOPQRSTUVWXYZ0123456789';449 let first = true;450 let value = '';451 while (true) {452 char = _token(context);453 if (char == undefined454 || (first ? identValidFirstChar.indexOf(char) : identValidChar.indexOf(char)) == -1) {455 context.position = context.previous;456 return {457 kind: 'identifier',458 start,459 end: context.position,460 text: context.original.substr(start.offset, context.position.offset),461 value,462 comments,463 };464 }465 value += char;466 first = false;467 }468}469/**470 * Read a property from the context. A property is a string or (in Loose mode only) a number or471 * an identifier, followed by a colon `:`.472 * @private473 */474function _readProperty(context, comments = _readBlanks(context)) {475 const start = context.position;476 let key;477 if ((context.mode & JsonParseMode.IdentifierKeyNamesAllowed) != 0) {478 const top = _peek(context);479 if (top == '"' || top == '\'') {480 key = _readString(context);481 }482 else {483 key = _readIdentifier(context);484 }485 }486 else {487 key = _readString(context);488 }489 _readBlanks(context);490 _token(context, ':');491 const value = _readValue(context);492 const end = context.position;493 return {494 kind: 'keyvalue',495 key,496 value,497 start,498 end,499 text: context.original.substring(start.offset, end.offset),500 comments,501 };502}503/**504 * Read an object of properties -> JSON values from the context.505 * @private506 */507function _readObject(context, comments = _readBlanks(context)) {508 const start = context.position;509 // Consume the first delimiter.510 _token(context, '{');511 const value = {};512 const properties = [];513 _readBlanks(context);514 if (_peek(context) != '}') {515 const property = _readProperty(context);516 value[property.key.value] = property.value.value;517 properties.push(property);518 while (_peek(context) != '}') {519 _token(context, ',');520 const propertyComments = _readBlanks(context);521 if ((context.mode & JsonParseMode.TrailingCommasAllowed) !== 0 && _peek(context) === '}') {522 break;523 }524 const property = _readProperty(context, propertyComments);525 value[property.key.value] = property.value.value;526 properties.push(property);527 }528 }529 _token(context, '}');530 return {531 kind: 'object',532 properties,533 start,534 end: context.position,535 value,536 text: context.original.substring(start.offset, context.position.offset),537 comments,538 };539}540/**541 * Remove any blank character or comments (in Loose mode) from the context, returning an array542 * of comments if any are found.543 * @private544 */545function _readBlanks(context) {546 if ((context.mode & JsonParseMode.CommentsAllowed) != 0) {547 const comments = [];548 while (true) {549 const char = context.original[context.position.offset];550 if (char == '/' && context.original[context.position.offset + 1] == '*') {551 const start = context.position;552 // Multi line comment.553 _next(context);554 _next(context);555 while (context.original[context.position.offset] != '*'556 || context.original[context.position.offset + 1] != '/') {557 _next(context);558 if (context.position.offset >= context.original.length) {559 throw new UnexpectedEndOfInputException(context);560 }561 }562 // Remove "*/".563 _next(context);564 _next(context);565 comments.push({566 kind: 'multicomment',567 start,568 end: context.position,569 text: context.original.substring(start.offset, context.position.offset),570 content: context.original.substring(start.offset + 2, context.position.offset - 2),571 });572 }573 else if (char == '/' && context.original[context.position.offset + 1] == '/') {574 const start = context.position;575 // Multi line comment.576 _next(context);577 _next(context);578 while (context.original[context.position.offset] != '\n') {579 _next(context);580 if (context.position.offset >= context.original.length) {581 break;582 }583 }584 // Remove "\n".585 if (context.position.offset < context.original.length) {586 _next(context);587 }588 comments.push({589 kind: 'comment',590 start,591 end: context.position,592 text: context.original.substring(start.offset, context.position.offset),593 content: context.original.substring(start.offset + 2, context.position.offset - 1),594 });595 }596 else if (char == ' ' || char == '\t' || char == '\n' || char == '\r' || char == '\f') {597 _next(context);598 }599 else {600 break;601 }602 }603 return comments;604 }605 else {606 let char = context.original[context.position.offset];607 while (char == ' ' || char == '\t' || char == '\n' || char == '\r' || char == '\f') {608 _next(context);609 char = context.original[context.position.offset];610 }611 return [];612 }613}614/**615 * Read a JSON value from the context, which can be any form of JSON value.616 * @private617 */618function _readValue(context, comments = _readBlanks(context)) {619 let result;620 // Clean up before.621 const char = _peek(context);622 switch (char) {623 case undefined:624 throw new UnexpectedEndOfInputException(context);625 case '-':626 case '0':627 case '1':628 case '2':629 case '3':630 case '4':631 case '5':632 case '6':633 case '7':634 case '8':635 case '9':636 result = _readNumber(context, comments);637 break;638 case '.':639 case '+':640 if ((context.mode & JsonParseMode.LaxNumberParsingAllowed) == 0) {641 throw new InvalidJsonCharacterException(context);642 }643 result = _readNumber(context, comments);644 break;645 case '\'':646 case '"':647 result = _readString(context, comments);648 break;649 case 'I':650 if ((context.mode & JsonParseMode.NumberConstantsAllowed) == 0) {651 throw new InvalidJsonCharacterException(context);652 }653 result = _readNumber(context, comments);654 break;655 case 'N':656 if ((context.mode & JsonParseMode.NumberConstantsAllowed) == 0) {657 throw new InvalidJsonCharacterException(context);658 }659 result = _readNaN(context, comments);660 break;661 case 't':662 result = _readTrue(context, comments);663 break;664 case 'f':665 result = _readFalse(context, comments);666 break;667 case 'n':668 result = _readNull(context, comments);669 break;670 case '[':671 result = _readArray(context, comments);672 break;673 case '{':674 result = _readObject(context, comments);675 break;676 default:677 throw new InvalidJsonCharacterException(context);678 }679 // Clean up after.680 _readBlanks(context);681 return result;682}683/**684 * The Parse mode used for parsing the JSON string.685 */686var JsonParseMode;687(function (JsonParseMode) {688 JsonParseMode[JsonParseMode["Strict"] = 0] = "Strict";689 JsonParseMode[JsonParseMode["CommentsAllowed"] = 1] = "CommentsAllowed";690 JsonParseMode[JsonParseMode["SingleQuotesAllowed"] = 2] = "SingleQuotesAllowed";691 JsonParseMode[JsonParseMode["IdentifierKeyNamesAllowed"] = 4] = "IdentifierKeyNamesAllowed";692 JsonParseMode[JsonParseMode["TrailingCommasAllowed"] = 8] = "TrailingCommasAllowed";693 JsonParseMode[JsonParseMode["HexadecimalNumberAllowed"] = 16] = "HexadecimalNumberAllowed";694 JsonParseMode[JsonParseMode["MultiLineStringAllowed"] = 32] = "MultiLineStringAllowed";695 JsonParseMode[JsonParseMode["LaxNumberParsingAllowed"] = 64] = "LaxNumberParsingAllowed";696 JsonParseMode[JsonParseMode["NumberConstantsAllowed"] = 128] = "NumberConstantsAllowed";697 JsonParseMode[JsonParseMode["Default"] = 0] = "Default";698 JsonParseMode[JsonParseMode["Loose"] = 255] = "Loose";699 JsonParseMode[JsonParseMode["Json"] = 0] = "Json";700 JsonParseMode[JsonParseMode["Json5"] = 255] = "Json5";701})(JsonParseMode = exports.JsonParseMode || (exports.JsonParseMode = {}));702/**703 * Parse the JSON string and return its AST. The AST may be losing data (end comments are704 * discarded for example, and space characters are not represented in the AST), but all values705 * will have a single node in the AST (a 1-to-1 mapping).706 * @param input The string to use.707 * @param mode The mode to parse the input with. {@see JsonParseMode}.708 * @returns {JsonAstNode} The root node of the value of the AST.709 */710function parseJsonAst(input, mode = JsonParseMode.Default) {711 if (mode == JsonParseMode.Default) {712 mode = JsonParseMode.Strict;713 }714 const context = {715 position: { offset: 0, line: 0, character: 0 },716 previous: { offset: 0, line: 0, character: 0 },717 original: input,718 comments: undefined,719 mode,720 };721 const ast = _readValue(context);722 if (context.position.offset < input.length) {723 const rest = input.substr(context.position.offset);724 const i = rest.length > 20 ? rest.substr(0, 20) + '...' : rest;725 throw new Error(`Expected end of file, got "${i}" at `726 + `${context.position.line}:${context.position.character}.`);727 }728 return ast;729}730exports.parseJsonAst = parseJsonAst;731/**732 * Parse a JSON string into its value. This discards the AST and only returns the value itself.733 *734 * If a path option is pass, it also absorbs JSON parsing errors and return a new error with the735 * path in it. Useful for showing errors when parsing from a file.736 *737 * @param input The string to parse.738 * @param mode The mode to parse the input with. {@see JsonParseMode}.739 * @param options Additional optinos for parsing.740 * @returns {JsonValue} The value represented by the JSON string.741 */742function parseJson(input, mode = JsonParseMode.Default, options) {743 try {744 // Try parsing for the fastest path available, if error, uses our own parser for better errors.745 if (mode == JsonParseMode.Strict) {746 try {747 return JSON.parse(input);748 }749 catch (err) {750 return parseJsonAst(input, mode).value;751 }752 }753 return parseJsonAst(input, mode).value;754 }755 catch (e) {756 if (options && options.path && e instanceof JsonException) {757 throw new PathSpecificJsonException(options.path, e);758 }759 throw e;760 }761}...
LZString.js
Source:LZString.js
1// Copyright (c) 2013 Pieroxy <pieroxy@pieroxy.net>2// This work is free. You can redistribute it and/or modify it3// under the terms of the WTFPL, Version 24// For more information see LICENSE.txt or http://www.wtfpl.net/5//6// For more information, the home page:7// http://pieroxy.net/blog/pages/lz-string/testing.html8// https://github.com/pieroxy/lz-string/blob/master/libs/lz-string.js9//10// LZ-based compression algorithm, version 1.4.411var LZString = (function() {12 // private property13 var f = String.fromCharCode;14 var keyStrBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";15 var keyStrUriSafe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$";16 var baseReverseDic = {};17 function getBaseValue(alphabet, character) {18 if (!baseReverseDic[alphabet]) {19 baseReverseDic[alphabet] = {};20 for (var i=0 ; i<alphabet.length ; i++) {21 baseReverseDic[alphabet][alphabet.charAt(i)] = i;22 }23 }24 return baseReverseDic[alphabet][character];25 }26 var LZString = {27 compressToBase64 : function (input) {28 if (input == null) return "";29 var res = LZString._compress(input, 6, function(a){return keyStrBase64.charAt(a);});30 switch (res.length % 4) { // To produce valid Base6431 default: // When could this happen ?32 case 0 : return res;33 case 1 : return res+"===";34 case 2 : return res+"==";35 case 3 : return res+"=";36 }37 },38 decompressFromBase64 : function (input) {39 if (input == null) return "";40 if (input == "") return null;41 return LZString._decompress(input.length, 32, function(index) { return getBaseValue(keyStrBase64, input.charAt(index)); });42 },43 compressToUTF16 : function (input) {44 if (input == null) return "";45 return LZString._compress(input, 15, function(a){return f(a+32);}) + " ";46 },47 decompressFromUTF16: function (compressed) {48 if (compressed == null) return "";49 if (compressed == "") return null;50 return LZString._decompress(compressed.length, 16384, function(index) { return compressed.charCodeAt(index) - 32; });51 },52 //compress into uint8array (UCS-2 big endian format)53 compressToUint8Array: function (uncompressed) {54 var compressed = LZString.compress(uncompressed);55 var buf=new Uint8Array(compressed.length*2); // 2 bytes per character56 for (var i=0, TotalLen=compressed.length; i<TotalLen; i++) {57 var current_value = compressed.charCodeAt(i);58 buf[i*2] = current_value >>> 8;59 buf[i*2+1] = current_value % 256;60 }61 return buf;62 },63 //decompress from uint8array (UCS-2 big endian format)64 decompressFromUint8Array:function (compressed) {65 if (compressed===null || compressed===undefined){66 return LZString.decompress(compressed);67 } else {68 var buf=new Array(compressed.length/2); // 2 bytes per character69 for (var i=0, TotalLen=buf.length; i<TotalLen; i++) {70 buf[i]=compressed[i*2]*256+compressed[i*2+1];71 }72 var result = [];73 buf.forEach(function (c) {74 result.push(f(c));75 });76 return LZString.decompress(result.join(''));77 }78 },79 //compress into a string that is already URI encoded80 compressToEncodedURIComponent: function (input) {81 if (input == null) return "";82 return LZString._compress(input, 6, function(a){return keyStrUriSafe.charAt(a);});83 },84 //decompress from an output of compressToEncodedURIComponent85 decompressFromEncodedURIComponent:function (input) {86 if (input == null) return "";87 if (input == "") return null;88 input = input.replace(/ /g, "+");89 return LZString._decompress(input.length, 32, function(index) { return getBaseValue(keyStrUriSafe, input.charAt(index)); });90 },91 compress: function (uncompressed) {92 return LZString._compress(uncompressed, 16, function(a){return f(a);});93 },94 _compress: function (uncompressed, bitsPerChar, getCharFromInt) {95 if (uncompressed == null) return "";96 var i, value,97 context_dictionary= {},98 context_dictionaryToCreate= {},99 context_c="",100 context_wc="",101 context_w="",102 context_enlargeIn= 2, // Compensate for the first entry which should not count103 context_dictSize= 3,104 context_numBits= 2,105 context_data=[],106 context_data_val=0,107 context_data_position=0,108 ii;109 for (ii = 0; ii < uncompressed.length; ii += 1) {110 context_c = uncompressed.charAt(ii);111 if (!Object.prototype.hasOwnProperty.call(context_dictionary,context_c)) {112 context_dictionary[context_c] = context_dictSize++;113 context_dictionaryToCreate[context_c] = true;114 }115 context_wc = context_w + context_c;116 if (Object.prototype.hasOwnProperty.call(context_dictionary,context_wc)) {117 context_w = context_wc;118 } else {119 if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) {120 if (context_w.charCodeAt(0)<256) {121 for (i=0 ; i<context_numBits ; i++) {122 context_data_val = (context_data_val << 1);123 if (context_data_position == bitsPerChar-1) {124 context_data_position = 0;125 context_data.push(getCharFromInt(context_data_val));126 context_data_val = 0;127 } else {128 context_data_position++;129 }130 }131 value = context_w.charCodeAt(0);132 for (i=0 ; i<8 ; i++) {133 context_data_val = (context_data_val << 1) | (value&1);134 if (context_data_position == bitsPerChar-1) {135 context_data_position = 0;136 context_data.push(getCharFromInt(context_data_val));137 context_data_val = 0;138 } else {139 context_data_position++;140 }141 value = value >> 1;142 }143 } else {144 value = 1;145 for (i=0 ; i<context_numBits ; i++) {146 context_data_val = (context_data_val << 1) | value;147 if (context_data_position ==bitsPerChar-1) {148 context_data_position = 0;149 context_data.push(getCharFromInt(context_data_val));150 context_data_val = 0;151 } else {152 context_data_position++;153 }154 value = 0;155 }156 value = context_w.charCodeAt(0);157 for (i=0 ; i<16 ; i++) {158 context_data_val = (context_data_val << 1) | (value&1);159 if (context_data_position == bitsPerChar-1) {160 context_data_position = 0;161 context_data.push(getCharFromInt(context_data_val));162 context_data_val = 0;163 } else {164 context_data_position++;165 }166 value = value >> 1;167 }168 }169 context_enlargeIn--;170 if (context_enlargeIn == 0) {171 context_enlargeIn = Math.pow(2, context_numBits);172 context_numBits++;173 }174 delete context_dictionaryToCreate[context_w];175 } else {176 value = context_dictionary[context_w];177 for (i=0 ; i<context_numBits ; i++) {178 context_data_val = (context_data_val << 1) | (value&1);179 if (context_data_position == bitsPerChar-1) {180 context_data_position = 0;181 context_data.push(getCharFromInt(context_data_val));182 context_data_val = 0;183 } else {184 context_data_position++;185 }186 value = value >> 1;187 }188 }189 context_enlargeIn--;190 if (context_enlargeIn == 0) {191 context_enlargeIn = Math.pow(2, context_numBits);192 context_numBits++;193 }194 // Add wc to the dictionary.195 context_dictionary[context_wc] = context_dictSize++;196 context_w = String(context_c);197 }198 }199 // Output the code for w.200 if (context_w !== "") {201 if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate,context_w)) {202 if (context_w.charCodeAt(0)<256) {203 for (i=0 ; i<context_numBits ; i++) {204 context_data_val = (context_data_val << 1);205 if (context_data_position == bitsPerChar-1) {206 context_data_position = 0;207 context_data.push(getCharFromInt(context_data_val));208 context_data_val = 0;209 } else {210 context_data_position++;211 }212 }213 value = context_w.charCodeAt(0);214 for (i=0 ; i<8 ; i++) {215 context_data_val = (context_data_val << 1) | (value&1);216 if (context_data_position == bitsPerChar-1) {217 context_data_position = 0;218 context_data.push(getCharFromInt(context_data_val));219 context_data_val = 0;220 } else {221 context_data_position++;222 }223 value = value >> 1;224 }225 } else {226 value = 1;227 for (i=0 ; i<context_numBits ; i++) {228 context_data_val = (context_data_val << 1) | value;229 if (context_data_position == bitsPerChar-1) {230 context_data_position = 0;231 context_data.push(getCharFromInt(context_data_val));232 context_data_val = 0;233 } else {234 context_data_position++;235 }236 value = 0;237 }238 value = context_w.charCodeAt(0);239 for (i=0 ; i<16 ; i++) {240 context_data_val = (context_data_val << 1) | (value&1);241 if (context_data_position == bitsPerChar-1) {242 context_data_position = 0;243 context_data.push(getCharFromInt(context_data_val));244 context_data_val = 0;245 } else {246 context_data_position++;247 }248 value = value >> 1;249 }250 }251 context_enlargeIn--;252 if (context_enlargeIn == 0) {253 context_enlargeIn = Math.pow(2, context_numBits);254 context_numBits++;255 }256 delete context_dictionaryToCreate[context_w];257 } else {258 value = context_dictionary[context_w];259 for (i=0 ; i<context_numBits ; i++) {260 context_data_val = (context_data_val << 1) | (value&1);261 if (context_data_position == bitsPerChar-1) {262 context_data_position = 0;263 context_data.push(getCharFromInt(context_data_val));264 context_data_val = 0;265 } else {266 context_data_position++;267 }268 value = value >> 1;269 }270 }271 context_enlargeIn--;272 if (context_enlargeIn == 0) {273 context_enlargeIn = Math.pow(2, context_numBits);274 context_numBits++;275 }276 }277 // Mark the end of the stream278 value = 2;279 for (i=0 ; i<context_numBits ; i++) {280 context_data_val = (context_data_val << 1) | (value&1);281 if (context_data_position == bitsPerChar-1) {282 context_data_position = 0;283 context_data.push(getCharFromInt(context_data_val));284 context_data_val = 0;285 } else {286 context_data_position++;287 }288 value = value >> 1;289 }290 // Flush the last char291 while (true) {292 context_data_val = (context_data_val << 1);293 if (context_data_position == bitsPerChar-1) {294 context_data.push(getCharFromInt(context_data_val));295 break;296 }297 else context_data_position++;298 }299 return context_data.join('');300 },301 decompress: function (compressed) {302 if (compressed == null) return "";303 if (compressed == "") return null;304 return LZString._decompress(compressed.length, 32768, function(index) { return compressed.charCodeAt(index); });305 },306 _decompress: function (length, resetValue, getNextValue) {307 var dictionary = [],308 next,309 enlargeIn = 4,310 dictSize = 4,311 numBits = 3,312 entry = "",313 result = [],314 i,315 w,316 bits, resb, maxpower, power,317 c,318 data = {val:getNextValue(0), position:resetValue, index:1};319 for (i = 0; i < 3; i += 1) {320 dictionary[i] = i;321 }322 bits = 0;323 maxpower = Math.pow(2,2);324 power=1;325 while (power!=maxpower) {326 resb = data.val & data.position;327 data.position >>= 1;328 if (data.position == 0) {329 data.position = resetValue;330 data.val = getNextValue(data.index++);331 }332 bits |= (resb>0 ? 1 : 0) * power;333 power <<= 1;334 }335 switch (next = bits) {336 case 0:337 bits = 0;338 maxpower = Math.pow(2,8);339 power=1;340 while (power!=maxpower) {341 resb = data.val & data.position;342 data.position >>= 1;343 if (data.position == 0) {344 data.position = resetValue;345 data.val = getNextValue(data.index++);346 }347 bits |= (resb>0 ? 1 : 0) * power;348 power <<= 1;349 }350 c = f(bits);351 break;352 case 1:353 bits = 0;354 maxpower = Math.pow(2,16);355 power=1;356 while (power!=maxpower) {357 resb = data.val & data.position;358 data.position >>= 1;359 if (data.position == 0) {360 data.position = resetValue;361 data.val = getNextValue(data.index++);362 }363 bits |= (resb>0 ? 1 : 0) * power;364 power <<= 1;365 }366 c = f(bits);367 break;368 case 2:369 return "";370 }371 dictionary[3] = c;372 w = c;373 result.push(c);374 while (true) {375 if (data.index > length) {376 return "";377 }378 bits = 0;379 maxpower = Math.pow(2,numBits);380 power=1;381 while (power!=maxpower) {382 resb = data.val & data.position;383 data.position >>= 1;384 if (data.position == 0) {385 data.position = resetValue;386 data.val = getNextValue(data.index++);387 }388 bits |= (resb>0 ? 1 : 0) * power;389 power <<= 1;390 }391 switch (c = bits) {392 case 0:393 bits = 0;394 maxpower = Math.pow(2,8);395 power=1;396 while (power!=maxpower) {397 resb = data.val & data.position;398 data.position >>= 1;399 if (data.position == 0) {400 data.position = resetValue;401 data.val = getNextValue(data.index++);402 }403 bits |= (resb>0 ? 1 : 0) * power;404 power <<= 1;405 }406 dictionary[dictSize++] = f(bits);407 c = dictSize-1;408 enlargeIn--;409 break;410 case 1:411 bits = 0;412 maxpower = Math.pow(2,16);413 power=1;414 while (power!=maxpower) {415 resb = data.val & data.position;416 data.position >>= 1;417 if (data.position == 0) {418 data.position = resetValue;419 data.val = getNextValue(data.index++);420 }421 bits |= (resb>0 ? 1 : 0) * power;422 power <<= 1;423 }424 dictionary[dictSize++] = f(bits);425 c = dictSize-1;426 enlargeIn--;427 break;428 case 2:429 return result.join('');430 }431 if (enlargeIn == 0) {432 enlargeIn = Math.pow(2, numBits);433 numBits++;434 }435 if (dictionary[c]) {436 entry = dictionary[c];437 } else {438 if (c === dictSize) {439 entry = w + w.charAt(0);440 } else {441 return null;442 }443 }444 result.push(entry);445 // Add w+entry[0] to the dictionary.446 dictionary[dictSize++] = w + entry.charAt(0);447 enlargeIn--;448 w = entry;449 if (enlargeIn == 0) {450 enlargeIn = Math.pow(2, numBits);451 numBits++;452 }453 }454 }455 };456 return LZString;457})();458if (typeof define === 'function' && define.amd) {459 define(function () { return LZString; });460} else if( typeof module !== 'undefined' && module != null ) {461 module.exports = LZString462} else if( typeof angular !== 'undefined' && angular != null ) {463 angular.module('LZString', [])464 .factory('LZString', function () {465 return LZString;466 });...
read-sources.js
Source:read-sources.js
1var fs = require('fs');2var path = require('path');3var applySourceMaps = require('./apply-source-maps');4var extractImportUrlAndMedia = require('./extract-import-url-and-media');5var isAllowedResource = require('./is-allowed-resource');6var loadOriginalSources = require('./load-original-sources');7var normalizePath = require('./normalize-path');8var rebase = require('./rebase');9var rebaseLocalMap = require('./rebase-local-map');10var rebaseRemoteMap = require('./rebase-remote-map');11var restoreImport = require('./restore-import');12var tokenize = require('../tokenizer/tokenize');13var Token = require('../tokenizer/token');14var Marker = require('../tokenizer/marker');15var hasProtocol = require('../utils/has-protocol');16var isImport = require('../utils/is-import');17var isRemoteResource = require('../utils/is-remote-resource');18var UNKNOWN_URI = 'uri:unknown';19function readSources(input, context, callback) {20 return doReadSources(input, context, function (tokens) {21 return applySourceMaps(tokens, context, function () {22 return loadOriginalSources(context, function () { return callback(tokens); });23 });24 });25}26function doReadSources(input, context, callback) {27 if (typeof input == 'string') {28 return fromString(input, context, callback);29 } else if (Buffer.isBuffer(input)) {30 return fromString(input.toString(), context, callback);31 } else if (Array.isArray(input)) {32 return fromArray(input, context, callback);33 } else if (typeof input == 'object') {34 return fromHash(input, context, callback);35 }36}37function fromString(input, context, callback) {38 context.source = undefined;39 context.sourcesContent[undefined] = input;40 context.stats.originalSize += input.length;41 return fromStyles(input, context, { inline: context.options.inline }, callback);42}43function fromArray(input, context, callback) {44 var inputAsImports = input.reduce(function (accumulator, uriOrHash) {45 if (typeof uriOrHash === 'string') {46 return addStringSource(uriOrHash, accumulator);47 } else {48 return addHashSource(uriOrHash, context, accumulator);49 }50 }, []);51 return fromStyles(inputAsImports.join(''), context, { inline: ['all'] }, callback);52}53function fromHash(input, context, callback) {54 var inputAsImports = addHashSource(input, context, []);55 return fromStyles(inputAsImports.join(''), context, { inline: ['all'] }, callback);56}57function addStringSource(input, imports) {58 imports.push(restoreAsImport(normalizeUri(input)));59 return imports;60}61function addHashSource(input, context, imports) {62 var uri;63 var normalizedUri;64 var source;65 for (uri in input) {66 source = input[uri];67 normalizedUri = normalizeUri(uri);68 imports.push(restoreAsImport(normalizedUri));69 context.sourcesContent[normalizedUri] = source.styles;70 if (source.sourceMap) {71 trackSourceMap(source.sourceMap, normalizedUri, context);72 }73 }74 return imports;75}76function normalizeUri(uri) {77 var currentPath = path.resolve('');78 var absoluteUri;79 var relativeToCurrentPath;80 var normalizedUri;81 if (isRemoteResource(uri)) {82 return uri;83 }84 absoluteUri = path.isAbsolute(uri) ?85 uri :86 path.resolve(uri);87 relativeToCurrentPath = path.relative(currentPath, absoluteUri);88 normalizedUri = normalizePath(relativeToCurrentPath);89 return normalizedUri;90}91function trackSourceMap(sourceMap, uri, context) {92 var parsedMap = typeof sourceMap == 'string' ?93 JSON.parse(sourceMap) :94 sourceMap;95 var rebasedMap = isRemoteResource(uri) ?96 rebaseRemoteMap(parsedMap, uri) :97 rebaseLocalMap(parsedMap, uri || UNKNOWN_URI, context.options.rebaseTo);98 context.inputSourceMapTracker.track(uri, rebasedMap);99}100function restoreAsImport(uri) {101 return restoreImport('url(' + uri + ')', '') + Marker.SEMICOLON;102}103function fromStyles(styles, context, parentInlinerContext, callback) {104 var tokens;105 var rebaseConfig = {};106 if (!context.source) {107 rebaseConfig.fromBase = path.resolve('');108 rebaseConfig.toBase = context.options.rebaseTo;109 } else if (isRemoteResource(context.source)) {110 rebaseConfig.fromBase = context.source;111 rebaseConfig.toBase = context.source;112 } else if (path.isAbsolute(context.source)) {113 rebaseConfig.fromBase = path.dirname(context.source);114 rebaseConfig.toBase = context.options.rebaseTo;115 } else {116 rebaseConfig.fromBase = path.dirname(path.resolve(context.source));117 rebaseConfig.toBase = context.options.rebaseTo;118 }119 tokens = tokenize(styles, context);120 tokens = rebase(tokens, context.options.rebase, context.validator, rebaseConfig);121 return allowsAnyImports(parentInlinerContext.inline) ?122 inline(tokens, context, parentInlinerContext, callback) :123 callback(tokens);124}125function allowsAnyImports(inline) {126 return !(inline.length == 1 && inline[0] == 'none');127}128function inline(tokens, externalContext, parentInlinerContext, callback) {129 var inlinerContext = {130 afterContent: false,131 callback: callback,132 errors: externalContext.errors,133 externalContext: externalContext,134 fetch: externalContext.options.fetch,135 inlinedStylesheets: parentInlinerContext.inlinedStylesheets || externalContext.inlinedStylesheets,136 inline: parentInlinerContext.inline,137 inlineRequest: externalContext.options.inlineRequest,138 inlineTimeout: externalContext.options.inlineTimeout,139 isRemote: parentInlinerContext.isRemote || false,140 localOnly: externalContext.localOnly,141 outputTokens: [],142 rebaseTo: externalContext.options.rebaseTo,143 sourceTokens: tokens,144 warnings: externalContext.warnings145 };146 return doInlineImports(inlinerContext);147}148function doInlineImports(inlinerContext) {149 var token;150 var i, l;151 for (i = 0, l = inlinerContext.sourceTokens.length; i < l; i++) {152 token = inlinerContext.sourceTokens[i];153 if (token[0] == Token.AT_RULE && isImport(token[1])) {154 inlinerContext.sourceTokens.splice(0, i);155 return inlineStylesheet(token, inlinerContext);156 } else if (token[0] == Token.AT_RULE || token[0] == Token.COMMENT) {157 inlinerContext.outputTokens.push(token);158 } else {159 inlinerContext.outputTokens.push(token);160 inlinerContext.afterContent = true;161 }162 }163 inlinerContext.sourceTokens = [];164 return inlinerContext.callback(inlinerContext.outputTokens);165}166function inlineStylesheet(token, inlinerContext) {167 var uriAndMediaQuery = extractImportUrlAndMedia(token[1]);168 var uri = uriAndMediaQuery[0];169 var mediaQuery = uriAndMediaQuery[1];170 var metadata = token[2];171 return isRemoteResource(uri) ?172 inlineRemoteStylesheet(uri, mediaQuery, metadata, inlinerContext) :173 inlineLocalStylesheet(uri, mediaQuery, metadata, inlinerContext);174}175function inlineRemoteStylesheet(uri, mediaQuery, metadata, inlinerContext) {176 var isAllowed = isAllowedResource(uri, true, inlinerContext.inline);177 var originalUri = uri;178 var isLoaded = uri in inlinerContext.externalContext.sourcesContent;179 var isRuntimeResource = !hasProtocol(uri);180 if (inlinerContext.inlinedStylesheets.indexOf(uri) > -1) {181 inlinerContext.warnings.push('Ignoring remote @import of "' + uri + '" as it has already been imported.');182 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);183 return doInlineImports(inlinerContext);184 } else if (inlinerContext.localOnly && inlinerContext.afterContent) {185 inlinerContext.warnings.push('Ignoring remote @import of "' + uri + '" as no callback given and after other content.');186 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);187 return doInlineImports(inlinerContext);188 } else if (isRuntimeResource) {189 inlinerContext.warnings.push('Skipping remote @import of "' + uri + '" as no protocol given.');190 inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1));191 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);192 return doInlineImports(inlinerContext);193 } else if (inlinerContext.localOnly && !isLoaded) {194 inlinerContext.warnings.push('Skipping remote @import of "' + uri + '" as no callback given.');195 inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1));196 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);197 return doInlineImports(inlinerContext);198 } else if (!isAllowed && inlinerContext.afterContent) {199 inlinerContext.warnings.push('Ignoring remote @import of "' + uri + '" as resource is not allowed and after other content.');200 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);201 return doInlineImports(inlinerContext);202 } else if (!isAllowed) {203 inlinerContext.warnings.push('Skipping remote @import of "' + uri + '" as resource is not allowed.');204 inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1));205 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);206 return doInlineImports(inlinerContext);207 }208 inlinerContext.inlinedStylesheets.push(uri);209 function whenLoaded(error, importedStyles) {210 if (error) {211 inlinerContext.errors.push('Broken @import declaration of "' + uri + '" - ' + error);212 return process.nextTick(function () {213 inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1));214 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);215 doInlineImports(inlinerContext);216 });217 }218 inlinerContext.inline = inlinerContext.externalContext.options.inline;219 inlinerContext.isRemote = true;220 inlinerContext.externalContext.source = originalUri;221 inlinerContext.externalContext.sourcesContent[uri] = importedStyles;222 inlinerContext.externalContext.stats.originalSize += importedStyles.length;223 return fromStyles(importedStyles, inlinerContext.externalContext, inlinerContext, function (importedTokens) {224 importedTokens = wrapInMedia(importedTokens, mediaQuery, metadata);225 inlinerContext.outputTokens = inlinerContext.outputTokens.concat(importedTokens);226 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);227 return doInlineImports(inlinerContext);228 });229 }230 return isLoaded ?231 whenLoaded(null, inlinerContext.externalContext.sourcesContent[uri]) :232 inlinerContext.fetch(uri, inlinerContext.inlineRequest, inlinerContext.inlineTimeout, whenLoaded);233}234function inlineLocalStylesheet(uri, mediaQuery, metadata, inlinerContext) {235 var currentPath = path.resolve('');236 var absoluteUri = path.isAbsolute(uri) ?237 path.resolve(currentPath, uri[0] == '/' ? uri.substring(1) : uri) :238 path.resolve(inlinerContext.rebaseTo, uri);239 var relativeToCurrentPath = path.relative(currentPath, absoluteUri);240 var importedStyles;241 var isAllowed = isAllowedResource(uri, false, inlinerContext.inline);242 var normalizedPath = normalizePath(relativeToCurrentPath);243 var isLoaded = normalizedPath in inlinerContext.externalContext.sourcesContent;244 if (inlinerContext.inlinedStylesheets.indexOf(absoluteUri) > -1) {245 inlinerContext.warnings.push('Ignoring local @import of "' + uri + '" as it has already been imported.');246 } else if (!isLoaded && (!fs.existsSync(absoluteUri) || !fs.statSync(absoluteUri).isFile())) {247 inlinerContext.errors.push('Ignoring local @import of "' + uri + '" as resource is missing.');248 } else if (!isAllowed && inlinerContext.afterContent) {249 inlinerContext.warnings.push('Ignoring local @import of "' + uri + '" as resource is not allowed and after other content.');250 } else if (inlinerContext.afterContent) {251 inlinerContext.warnings.push('Ignoring local @import of "' + uri + '" as after other content.');252 } else if (!isAllowed) {253 inlinerContext.warnings.push('Skipping local @import of "' + uri + '" as resource is not allowed.');254 inlinerContext.outputTokens = inlinerContext.outputTokens.concat(inlinerContext.sourceTokens.slice(0, 1));255 } else {256 importedStyles = isLoaded ?257 inlinerContext.externalContext.sourcesContent[normalizedPath] :258 fs.readFileSync(absoluteUri, 'utf-8');259 inlinerContext.inlinedStylesheets.push(absoluteUri);260 inlinerContext.inline = inlinerContext.externalContext.options.inline;261 inlinerContext.externalContext.source = normalizedPath;262 inlinerContext.externalContext.sourcesContent[normalizedPath] = importedStyles;263 inlinerContext.externalContext.stats.originalSize += importedStyles.length;264 return fromStyles(importedStyles, inlinerContext.externalContext, inlinerContext, function (importedTokens) {265 importedTokens = wrapInMedia(importedTokens, mediaQuery, metadata);266 inlinerContext.outputTokens = inlinerContext.outputTokens.concat(importedTokens);267 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);268 return doInlineImports(inlinerContext);269 });270 }271 inlinerContext.sourceTokens = inlinerContext.sourceTokens.slice(1);272 return doInlineImports(inlinerContext);273}274function wrapInMedia(tokens, mediaQuery, metadata) {275 if (mediaQuery) {276 return [[Token.NESTED_BLOCK, [[Token.NESTED_BLOCK_SCOPE, '@media ' + mediaQuery, metadata]], tokens]];277 } else {278 return tokens;279 }280}...
qgis2web_expressions.js
Source:qgis2web_expressions.js
1// Aggregates2// Color3// Conditionals4function fnc_coalesce(values, context) {5 for (i = 0; i < values.length; i++) {6 if (values[i] !== null) {7 return values[i];8 }9 10 }11 return 'ERROR';12};13// Conversions14// Custom15// Date and Time16// Fields and Values17// Fuzzy Matching18// General19// Geometry20function fnc_azimuth(values, context) {21 return false;22};23function fnc_project(values, context) {24 return false;25};26// Math27function fnc_abs(values, context) {28 return Math.abs(values[0]);29};30function fnc_degrees(values, context) {31 return values[0] * (180/Math.PI);32};33function fnc_radians(values, context) {34 return values[0] * (Math.PI/180);35};36function fnc_sqrt(values, context) {37 return Math.sqrt(values[0]);38};39function fnc_cos(values, context) {40 return Math.cos(values[0]);41};42function fnc_sin(values, context) {43 return Math.sin(values[0]);44};45function fnc_tan(values, context) {46 return Math.tan(values[0]);47};48function fnc_asin(values, context) {49 return Math.asin(values[0]);50};51function fnc_acos(values, context) {52 return Math.acos(values[0]);53};54function fnc_atan(values, context) {55 return Math.atan(values[0]);56};57function fnc_atan2(values, context) {58 return Math.atan2(values[0]);59};60function fnc_exp(values, context) {61 return Math.exp(values[0]);62};63function fnc_ln(values, context) {64 return Math.log(values[0]);65};66function fnc_log10(values, context) {67 return Math.log10(values[0]);68};69function fnc_log(values, context) {70 return Math.log(values[0]) / Math.log(values[1]);71};72function fnc_round(values, context) {73 return false;74};75function fnc_rand(values, context) {76 return Math.floor(Math.random()*(values[1]-values[0]+1)+values[0]);77};78function fnc_randf(values, context) {79 return Math.random()*(values[1]-values[0]+1)+values[0];80};81function fnc_max(values, context) {82 return Math.max.apply(this, values);83};84function fnc_min(values, context) {85 return Math.min.apply(this, values);86};87function fnc_clamp(values, context) {88 return false;89};90// Operators91// Record92// String93// TimeManager94// Variables95function fnc_scale_linear(values, context) {96 return false;97};98function fnc_scale_exp(values, context) {99 return false;100};101function fnc_floor(values, context) {102 return false;103};104function fnc_ceil(values, context) {105 return false;106};107function fnc_pi(values, context) {108 return false;109};110function fnc_to_int(values, context) {111 return false;112};113function fnc_to_real(values, context) {114 return false;115};116function fnc_to_string(values, context) {117 return false;118};119function fnc_to_datetime(values, context) {120 return false;121};122function fnc_to_date(values, context) {123 return false;124};125function fnc_to_time(values, context) {126 return false;127};128function fnc_to_interval(values, context) {129 return false;130};131function fnc_if(values, context) {132 return false;133};134function fnc_aggregate(values, context) {135 return false;136};137function fnc_relation_aggregate(values, context) {138 return false;139};140function fnc_count(values, context) {141 return false;142};143function fnc_count_distinct(values, context) {144 return false;145};146function fnc_count_missing(values, context) {147 return false;148};149function fnc_minimum(values, context) {150 return false;151};152function fnc_maximum(values, context) {153 return false;154};155function fnc_sum(values, context) {156 return false;157};158function fnc_mean(values, context) {159 return false;160};161function fnc_median(values, context) {162 return false;163};164function fnc_stdev(values, context) {165 return false;166};167function fnc_range(values, context) {168 return false;169};170function fnc_minority(values, context) {171 return false;172};173function fnc_majority(values, context) {174 return false;175};176function fnc_q1(values, context) {177 return false;178};179function fnc_q3(values, context) {180 return false;181};182function fnc_iqr(values, context) {183 return false;184};185function fnc_min_length(values, context) {186 return false;187};188function fnc_max_length(values, context) {189 return false;190};191function fnc_concatenate(values, context) {192 return false;193};194function fnc_regexp_match(values, context) {195 return false;196};197function fnc_now(values, context) {198 return false;199};200function fnc_age(values, context) {201 return false;202};203function fnc_year(values, context) {204 return false;205};206function fnc_month(values, context) {207 return false;208};209function fnc_week(values, context) {210 return false;211};212function fnc_day(values, context) {213 return false;214};215function fnc_hour(values, context) {216 return false;217};218function fnc_minute(values, context) {219 return false;220};221function fnc_second(values, context) {222 return false;223};224function fnc_day_of_week(values, context) {225 return false;226};227function fnc_lower(values, context) {228 return values[0].toLowerCase();229};230function fnc_upper(values, context) {231 return false;232};233function fnc_title(values, context) {234 return false;235};236function fnc_trim(values, context) {237 return false;238};239function fnc_levenshtein(values, context) {240 return false;241};242function fnc_longest_common_substring(values, context) {243 return false;244};245function fnc_hamming_distance(values, context) {246 return false;247};248function fnc_soundex(values, context) {249 return false;250};251function fnc_char(values, context) {252 return false;253};254function fnc_wordwrap(values, context) {255 return false;256};257function fnc_length(values, context) {258 return false;259};260function fnc_replace(values, context) {261 return false;262};263function fnc_regexp_replace(values, context) {264 return false;265};266function fnc_regexp_substr(values, context) {267 return false;268};269function fnc_substr(values, context) {270 return false;271};272function fnc_concat(values, context) {273 return false;274};275function fnc_strpos(values, context) {276 return false;277};278function fnc_left(values, context) {279 return false;280};281function fnc_right(values, context) {282 return false;283};284function fnc_rpad(values, context) {285 return false;286};287function fnc_lpad(values, context) {288 return false;289};290function fnc_format(values, context) {291 return false;292};293function fnc_format_number(values, context) {294 return false;295};296function fnc_format_date(values, context) {297 return false;298};299function fnc_color_rgb(values, context) {300 return false;301};302function fnc_color_rgba(values, context) {303 return false;304};305function fnc_ramp_color(values, context) {306 return false;307};308function fnc_color_hsl(values, context) {309 return false;310};311function fnc_color_hsla(values, context) {312 return false;313};314function fnc_color_hsv(values, context) {315 return false;316};317function fnc_color_hsva(values, context) {318 return false;319};320function fnc_color_cmyk(values, context) {321 return false;322};323function fnc_color_cmyka(values, context) {324 return false;325};326function fnc_color_part(values, context) {327 return false;328};329function fnc_darker(values, context) {330 return false;331};332function fnc_lighter(values, context) {333 return false;334};335function fnc_set_color_part(values, context) {336 return false;337};338function fnc_area(values, context) {339 return false;340};341function fnc_perimeter(values, context) {342 return false;343};344function fnc_x(values, context) {345 return false;346};347function fnc_y(values, context) {348 return false;349};350function fnc_z(values, context) {351 return false;352};353function fnc_m(values, context) {354 return false;355};356function fnc_point_n(values, context) {357 return false;358};359function fnc_start_point(values, context) {360 return false;361};362function fnc_end_point(values, context) {363 return false;364};365function fnc_nodes_to_points(values, context) {366 return false;367};368function fnc_segments_to_lines(values, context) {369 return false;370};371function fnc_make_point(values, context) {372 return false;373};374function fnc_make_point_m(values, context) {375 return false;376};377function fnc_make_line(values, context) {378 return false;379};380function fnc_make_polygon(values, context) {381 return false;382};383function fnc_x_min(values, context) {384 return false;385};386function fnc_x_max(values, context) {387 return false;388};389function fnc_y_min(values, context) {390 return false;391};392function fnc_y_max(values, context) {393 return false;394};395function fnc_geom_from_wkt(values, context) {396 return false;397};398function fnc_geom_from_gml(values, context) {399 return false;400};401function fnc_relate(values, context) {402 return false;403};404function fnc_intersects_bbox(values, context) {405 return false;406};407function fnc_disjoint(values, context) {408 return false;409};410function fnc_intersects(values, context) {411 return false;412};413function fnc_touches(values, context) {414 return false;415};416function fnc_crosses(values, context) {417 return false;418};419function fnc_contains(values, context) {420 return false;421};422function fnc_overlaps(values, context) {423 return false;424};425function fnc_within(values, context) {426 return false;427};428function fnc_translate(values, context) {429 return false;430};431function fnc_buffer(values, context) {432 return false;433};434function fnc_centroid(values, context) {435 return false;436};437function fnc_point_on_surface(values, context) {438 return false;439};440function fnc_reverse(values, context) {441 return false;442};443function fnc_exterior_ring(values, context) {444 return false;445};446function fnc_interior_ring_n(values, context) {447 return false;448};449function fnc_geometry_n(values, context) {450 return false;451};452function fnc_boundary(values, context) {453 return false;454};455function fnc_line_merge(values, context) {456 return false;457};458function fnc_bounds(values, context) {459 return false;460};461function fnc_num_points(values, context) {462 return false;463};464function fnc_num_interior_rings(values, context) {465 return false;466};467function fnc_num_rings(values, context) {468 return false;469};470function fnc_num_geometries(values, context) {471 return false;472};473function fnc_bounds_width(values, context) {474 return false;475};476function fnc_bounds_height(values, context) {477 return false;478};479function fnc_is_closed(values, context) {480 return false;481};482function fnc_convex_hull(values, context) {483 return false;484};485function fnc_difference(values, context) {486 return false;487};488function fnc_distance(values, context) {489 return false;490};491function fnc_intersection(values, context) {492 return false;493};494function fnc_sym_difference(values, context) {495 return false;496};497function fnc_combine(values, context) {498 return false;499};500function fnc_union(values, context) {501 return false;502};503function fnc_geom_to_wkt(values, context) {504 return false;505};506function fnc_geometry(values, context) {507 return false;508};509function fnc_transform(values, context) {510 return false;511};512function fnc_extrude(values, context) {513 return false;514};515function fnc_order_parts(values, context) {516 return false;517};518function fnc_closest_point(values, context) {519 return false;520};521function fnc_shortest_line(values, context) {522 return false;523};524function fnc_line_interpolate_point(values, context) {525 return false;526};527function fnc_line_interpolate_angle(values, context) {528 return false;529};530function fnc_line_locate_point(values, context) {531 return false;532};533function fnc_angle_at_vertex(values, context) {534 return false;535};536function fnc_distance_to_vertex(values, context) {537 return false;538};539function fnc_uuid(values, context) {540 return false;541};542function fnc_get_feature(values, context) {543 return false;544};545function fnc_layer_property(values, context) {546 return false;547};548function fnc_var(values, context) {549 return false;550};551function fnc_eval(values, context) {552 return false;553};554function fnc_attribute(values, context) {555 return false;556};557function fnc__specialcol_(values, context) {558 return false;559};560function fnc_project_color(values, context) {561 return false;...
repositoryViewContext.js
Source:repositoryViewContext.js
1cap.model("RepositoryViewContext", function ($q, $filter, HttpMethodVerbs) {2 return function RepositoryViewContext() {3 var repositoryViewContext = this;4 var children = {};5 var shortenContextUri = function (contextUri) {6 return repositoryViewContext.repositoryView.rootUri ? $filter('shortenUri')(contextUri, repositoryViewContext.repositoryView.rootUri) : contextUri;7 };8 var fetchContext = function (contextUri) {9 return repositoryViewContext.repositoryView.performRequest(repositoryViewContext.getMapping().load, {10 method: HttpMethodVerbs.GET,11 query: {12 contextUri: shortenContextUri(contextUri)13 }14 });15 };16 repositoryViewContext.before(function () {17 var defer = $q.defer();18 if (repositoryViewContext.fetch) {19 fetchContext(repositoryViewContext.uri).then(function (res) {20 angular.extend(repositoryViewContext, angular.fromJson(res.body).payload.RepositoryViewContext, {21 fetch: false22 });23 repositoryViewContext.repositoryView.cacheContext(repositoryViewContext);24 defer.resolve(repositoryViewContext);25 repositoryViewContext.ready().then(function () {26 if (repositoryViewContext.repositoryView.inTransaction()) {27 repositoryViewContext.repositoryView.startTransactionTimer();28 }29 });30 });31 } else {32 defer.resolve(repositoryViewContext);33 }34 return defer.promise;35 });36 repositoryViewContext.reloadContext = function () {37 var reloadPromise = fetchContext(repositoryViewContext.uri);38 reloadPromise.then(function (res) {39 angular.extend(repositoryViewContext, angular.fromJson(res.body).payload.RepositoryViewContext, {40 fetch: false41 });42 });43 return reloadPromise;44 };45 repositoryViewContext.getChildContext = function (triple) {46 if (!children[triple.object]) {47 children[triple.object] = new RepositoryViewContext({48 fetch: false49 });50 var cachedContext = repositoryViewContext.repositoryView.getCachedContext(triple.object);51 if (cachedContext) {52 angular.extend(children[triple.object], cachedContext);53 } else {54 fetchContext(triple.object).then(function (res) {55 angular.extend(children[triple.object], angular.fromJson(res.body).payload.RepositoryViewContext, {56 repositoryView: repositoryViewContext.repositoryView,57 uri: triple.object58 });59 repositoryViewContext.repositoryView.cacheContext(children[triple.object]);60 });61 }62 }63 return children[triple.object];64 };65 repositoryViewContext.getCachedChildContext = function (contextUri) {66 return children[contextUri];67 };68 repositoryViewContext.createContainer = function (metadata) {69 var createPromise = repositoryViewContext.repositoryView.performRequest(repositoryViewContext.getMapping().children, {70 method: HttpMethodVerbs.POST,71 query: {72 contextUri: shortenContextUri(repositoryViewContext.uri)73 },74 data: metadata75 });76 createPromise.then(function (res) {77 angular.extend(repositoryViewContext, angular.fromJson(res.body).payload.RepositoryViewContext);78 });79 return createPromise;80 };81 repositoryViewContext.removeContainers = function (containerTriples) {82 var promises = [];83 angular.forEach(containerTriples, function (containerTriple) {84 var removePromise = repositoryViewContext.repositoryView.performRequest(repositoryViewContext.getMapping().load, {85 method: HttpMethodVerbs.DELETE,86 query: {87 contextUri: shortenContextUri(containerTriple.subject)88 }89 });90 removePromise.then(function (res) {91 var children = repositoryViewContext.children;92 for (var i in children) {93 if (children.hasOwnProperty(i)) {94 var child = children[i];95 if (child.triple.object === containerTriple.subject) {96 children.splice(i, 1);97 break;98 }99 }100 }101 });102 promises.push(removePromise);103 });104 var allRemovePromses = $q.all(promises);105 return allRemovePromses;106 };107 repositoryViewContext.removeResources = function (resourceTriples) {108 var promises = [];109 angular.forEach(resourceTriples, function (resourceTriple) {110 var removePromise = repositoryViewContext.repositoryView.performRequest(repositoryViewContext.getMapping().resource, {111 method: HttpMethodVerbs.DELETE,112 query: {113 contextUri: shortenContextUri(resourceTriple.subject)114 }115 });116 removePromise.then(function (res) {117 var children = repositoryViewContext.children;118 for (var i in children) {119 if (children.hasOwnProperty(i)) {120 var child = children[i];121 if (child.triple.object === resourceTriple.subject) {122 children.splice(i, 1);123 break;124 }125 }126 }127 });128 promises.push(removePromise);129 });130 var allRemovePromses = $q.all(promises);131 return allRemovePromses;132 };133 repositoryViewContext.createResource = function (file) {134 var formData = new FormData();135 formData.append("file", file, file.name);136 var createPromise = repositoryViewContext.repositoryView.performRequest(repositoryViewContext.getMapping().resource, {137 method: HttpMethodVerbs.POST,138 headers: {139 "Content-Type": undefined140 },141 query: {142 contextUri: shortenContextUri(repositoryViewContext.uri)143 },144 data: formData145 });146 createPromise.then(function (res) {147 angular.extend(repositoryViewContext, angular.fromJson(res.body).payload.RepositoryViewContext);148 });149 return createPromise;150 };151 repositoryViewContext.refreshContext = function () {152 var refreshPromise = repositoryViewContext.repositoryView.performRequest(repositoryViewContext.getMapping().refreshContext, {153 method: HttpMethodVerbs.POST,154 query: {155 contextUri: repositoryViewContext.uri156 }157 });158 return refreshPromise;159 };160 repositoryViewContext.createMetadata = function (metadataTriples) {161 var promises = [];162 angular.forEach(metadataTriples, function (metadataTriple) {163 var createPromise = repositoryViewContext.repositoryView.performRequest(repositoryViewContext.getMapping().metadata, {164 method: HttpMethodVerbs.POST,165 query: {166 contextUri: shortenContextUri(repositoryViewContext.uri)167 },168 data: metadataTriple169 });170 createPromise.then(function (res) {171 angular.extend(repositoryViewContext, angular.fromJson(res.body).payload.RepositoryViewContext);172 });173 promises.push(createPromise);174 });175 var allCreatePromses = $q.all(promises);176 return allCreatePromses;177 };178 repositoryViewContext.removeMetadata = function (metadataTriples) {179 var promises = [];180 angular.forEach(metadataTriples, function (metadataTriple) {181 var removePromise = repositoryViewContext.repositoryView.performRequest(repositoryViewContext.getMapping().metadata, {182 method: HttpMethodVerbs.DELETE,183 query: {184 contextUri: shortenContextUri(repositoryViewContext.uri)185 },186 data: metadataTriple187 });188 removePromise.then(function (response) {189 var payload = angular.fromJson(response.body).payload;190 if (payload) {191 angular.extend(repositoryViewContext, payload.RepositoryViewContext);192 }193 });194 promises.push(removePromise);195 });196 var allRemovePromses = $q.all(promises);197 return allRemovePromses;198 };199 repositoryViewContext.updateMetadatum = function (metadataTriple, value) {200 var updatePromise = repositoryViewContext.repositoryView.performRequest(repositoryViewContext.getMapping().metadata, {201 method: HttpMethodVerbs.PUT,202 query: {203 contextUri: shortenContextUri(repositoryViewContext.uri),204 value: encodeURIComponent($filter("escapeLiteral")(value))205 },206 data: metadataTriple207 });208 return updatePromise;209 };210 repositoryViewContext.createVersion = function (form) {211 var versionPromise = repositoryViewContext.repositoryView.performRequest(repositoryViewContext.getMapping().version, {212 method: HttpMethodVerbs.POST,213 query: {214 contextUri: shortenContextUri(repositoryViewContext.uri),215 name: form.name216 }217 });218 versionPromise.then(function (apiRes) {219 var newContext = angular.fromJson(apiRes.body).payload.RepositoryViewContext;220 angular.extend(repositoryViewContext, newContext);221 if (form) {222 form.$setPristine();223 form.$setUntouched();224 form.name = "";225 }226 });227 return versionPromise;228 };229 repositoryViewContext.deleteVersion = function (versionContext) {230 return repositoryViewContext.repositoryView.performRequest(repositoryViewContext.getMapping().version, {231 method: HttpMethodVerbs.DELETE,232 query: {233 contextUri: shortenContextUri(versionContext.uri)234 }235 });236 };237 repositoryViewContext.revertVersion = function (versionContext) {238 var revertVersionPromise = repositoryViewContext.repositoryView.performRequest(repositoryViewContext.getMapping().version, {239 method: HttpMethodVerbs.PATCH,240 query: {241 contextUri: shortenContextUri(versionContext.uri)242 }243 });244 return revertVersionPromise;245 };246 repositoryViewContext.advancedUpdate = function (query) {247 var updatePromise = repositoryViewContext.repositoryView.performRequest(repositoryViewContext.getMapping().advancedQuery, {248 method: HttpMethodVerbs.POST,249 query: {250 contextUri: shortenContextUri(repositoryViewContext.uri)251 },252 data: query253 });254 updatePromise.then(function (res) {255 angular.extend(repositoryViewContext, angular.fromJson(res.body).payload.RepositoryViewContext);256 });257 return updatePromise;258 };259 var queryHelp = {};260 repositoryViewContext.getQueryHelp = function () {261 if (!queryHelp.message) {262 var updatePromise = repositoryViewContext.repositoryView.performRequest(repositoryViewContext.getMapping().advancedQuery, {263 method: HttpMethodVerbs.GET264 });265 updatePromise.then(function (res) {266 queryHelp.query = angular.fromJson(res.body).payload.String;267 });268 }269 return queryHelp;270 };271 return repositoryViewContext;272 };...
helpers.js
Source:helpers.js
1var emptyCharacter = '';2var Breaks = require('../options/format').Breaks;3var Spaces = require('../options/format').Spaces;4var Marker = require('../tokenizer/marker');5var Token = require('../tokenizer/token');6function supportsAfterClosingBrace(token) {7 return token[1][1] == 'background' || token[1][1] == 'transform' || token[1][1] == 'src';8}9function afterClosingBrace(token, valueIndex) {10 return token[valueIndex][1][token[valueIndex][1].length - 1] == Marker.CLOSE_ROUND_BRACKET;11}12function afterComma(token, valueIndex) {13 return token[valueIndex][1] == Marker.COMMA;14}15function afterSlash(token, valueIndex) {16 return token[valueIndex][1] == Marker.FORWARD_SLASH;17}18function beforeComma(token, valueIndex) {19 return token[valueIndex + 1] && token[valueIndex + 1][1] == Marker.COMMA;20}21function beforeSlash(token, valueIndex) {22 return token[valueIndex + 1] && token[valueIndex + 1][1] == Marker.FORWARD_SLASH;23}24function inFilter(token) {25 return token[1][1] == 'filter' || token[1][1] == '-ms-filter';26}27function disallowsSpace(context, token, valueIndex) {28 return !context.spaceAfterClosingBrace && supportsAfterClosingBrace(token) && afterClosingBrace(token, valueIndex) ||29 beforeSlash(token, valueIndex) ||30 afterSlash(token, valueIndex) ||31 beforeComma(token, valueIndex) ||32 afterComma(token, valueIndex);33}34function rules(context, tokens) {35 var store = context.store;36 for (var i = 0, l = tokens.length; i < l; i++) {37 store(context, tokens[i]);38 if (i < l - 1) {39 store(context, comma(context));40 }41 }42}43function body(context, tokens) {44 var lastPropertyAt = lastPropertyIndex(tokens);45 for (var i = 0, l = tokens.length; i < l; i++) {46 property(context, tokens, i, lastPropertyAt);47 }48}49function lastPropertyIndex(tokens) {50 var index = tokens.length - 1;51 for (; index >= 0; index--) {52 if (tokens[index][0] != Token.COMMENT) {53 break;54 }55 }56 return index;57}58function property(context, tokens, position, lastPropertyAt) {59 var store = context.store;60 var token = tokens[position];61 var isPropertyBlock = token[2][0] == Token.PROPERTY_BLOCK;62 var needsSemicolon;63 if ( context.format ) {64 if ( context.format.semicolonAfterLastProperty || isPropertyBlock ) {65 needsSemicolon = true;66 } else if ( position < lastPropertyAt ) {67 needsSemicolon = true;68 } else {69 needsSemicolon = false;70 }71 } else {72 needsSemicolon = position < lastPropertyAt || isPropertyBlock;73 }74 var isLast = position === lastPropertyAt;75 switch (token[0]) {76 case Token.AT_RULE:77 store(context, token);78 store(context, semicolon(context, Breaks.AfterProperty, false));79 break;80 case Token.AT_RULE_BLOCK:81 rules(context, token[1]);82 store(context, openBrace(context, Breaks.AfterRuleBegins, true));83 body(context, token[2]);84 store(context, closeBrace(context, Breaks.AfterRuleEnds, false, isLast));85 break;86 case Token.COMMENT:87 store(context, token);88 break;89 case Token.PROPERTY:90 store(context, token[1]);91 store(context, colon(context));92 value(context, token);93 store(context, needsSemicolon ? semicolon(context, Breaks.AfterProperty, isLast) : emptyCharacter);94 break;95 case Token.RAW:96 store(context, token);97 }98}99function value(context, token) {100 var store = context.store;101 var j, m;102 if (token[2][0] == Token.PROPERTY_BLOCK) {103 store(context, openBrace(context, Breaks.AfterBlockBegins, false));104 body(context, token[2][1]);105 store(context, closeBrace(context, Breaks.AfterBlockEnds, false, true));106 } else {107 for (j = 2, m = token.length; j < m; j++) {108 store(context, token[j]);109 if (j < m - 1 && (inFilter(token) || !disallowsSpace(context, token, j))) {110 store(context, Marker.SPACE);111 }112 }113 }114}115function allowsBreak(context, where) {116 return context.format && context.format.breaks[where];117}118function allowsSpace(context, where) {119 return context.format && context.format.spaces[where];120}121function openBrace(context, where, needsPrefixSpace) {122 if (context.format) {123 context.indentBy += context.format.indentBy;124 context.indentWith = context.format.indentWith.repeat(context.indentBy);125 return (needsPrefixSpace && allowsSpace(context, Spaces.BeforeBlockBegins) ? Marker.SPACE : emptyCharacter) +126 Marker.OPEN_CURLY_BRACKET +127 (allowsBreak(context, where) ? context.format.breakWith : emptyCharacter) +128 context.indentWith;129 } else {130 return Marker.OPEN_CURLY_BRACKET;131 }132}133function closeBrace(context, where, beforeBlockEnd, isLast) {134 if (context.format) {135 context.indentBy -= context.format.indentBy;136 context.indentWith = context.format.indentWith.repeat(context.indentBy);137 return (allowsBreak(context, Breaks.AfterProperty) || beforeBlockEnd && allowsBreak(context, Breaks.BeforeBlockEnds) ? context.format.breakWith : emptyCharacter) +138 context.indentWith +139 Marker.CLOSE_CURLY_BRACKET +140 (isLast ? emptyCharacter : (allowsBreak(context, where) ? context.format.breakWith : emptyCharacter) + context.indentWith);141 } else {142 return Marker.CLOSE_CURLY_BRACKET;143 }144}145function colon(context) {146 return context.format ?147 Marker.COLON + (allowsSpace(context, Spaces.BeforeValue) ? Marker.SPACE : emptyCharacter) :148 Marker.COLON;149}150function semicolon(context, where, isLast) {151 return context.format ?152 Marker.SEMICOLON + (isLast || !allowsBreak(context, where) ? emptyCharacter : context.format.breakWith + context.indentWith) :153 Marker.SEMICOLON;154}155function comma(context) {156 return context.format ?157 Marker.COMMA + (allowsBreak(context, Breaks.BetweenSelectors) ? context.format.breakWith : emptyCharacter) + context.indentWith :158 Marker.COMMA;159}160function all(context, tokens) {161 var store = context.store;162 var token;163 var isLast;164 var i, l;165 for (i = 0, l = tokens.length; i < l; i++) {166 token = tokens[i];167 isLast = i == l - 1;168 switch (token[0]) {169 case Token.AT_RULE:170 store(context, token);171 store(context, semicolon(context, Breaks.AfterAtRule, isLast));172 break;173 case Token.AT_RULE_BLOCK:174 rules(context, token[1]);175 store(context, openBrace(context, Breaks.AfterRuleBegins, true));176 body(context, token[2]);177 store(context, closeBrace(context, Breaks.AfterRuleEnds, false, isLast));178 break;179 case Token.NESTED_BLOCK:180 rules(context, token[1]);181 store(context, openBrace(context, Breaks.AfterBlockBegins, true));182 all(context, token[2]);183 store(context, closeBrace(context, Breaks.AfterBlockEnds, true, isLast));184 break;185 case Token.COMMENT:186 store(context, token);187 store(context, allowsBreak(context, Breaks.AfterComment) ? context.format.breakWith : emptyCharacter);188 break;189 case Token.RAW:190 store(context, token);191 break;192 case Token.RULE:193 rules(context, token[1]);194 store(context, openBrace(context, Breaks.AfterRuleBegins, true));195 body(context, token[2]);196 store(context, closeBrace(context, Breaks.AfterRuleEnds, false, isLast));197 break;198 }199 }200}201module.exports = {202 all: all,203 body: body,204 property: property,205 rules: rules,206 value: value...
node.js
Source:node.js
1/*2 MIT License http://www.opensource.org/licenses/mit-license.php3 Author Tobias Koppers @sokra4*/5"use strict";6const ResolverFactory = require("./ResolverFactory");7const NodeJsInputFileSystem = require("./NodeJsInputFileSystem");8const CachedInputFileSystem = require("./CachedInputFileSystem");9const nodeFileSystem = new CachedInputFileSystem(new NodeJsInputFileSystem(), 4000);10const nodeContext = {11 environments: [12 "node+es3+es5+process+native"13 ]14};15const asyncResolver = ResolverFactory.createResolver({16 extensions: [".js", ".json", ".node"],17 fileSystem: nodeFileSystem18});19module.exports = function resolve(context, path, request, resolveContext, callback) {20 if(typeof context === "string") {21 callback = resolveContext;22 resolveContext = request;23 request = path;24 path = context;25 context = nodeContext;26 }27 if(typeof callback !== "function") {28 callback = resolveContext;29 }30 asyncResolver.resolve(context, path, request, resolveContext, callback);31};32const syncResolver = ResolverFactory.createResolver({33 extensions: [".js", ".json", ".node"],34 useSyncFileSystemCalls: true,35 fileSystem: nodeFileSystem36});37module.exports.sync = function resolveSync(context, path, request) {38 if(typeof context === "string") {39 request = path;40 path = context;41 context = nodeContext;42 }43 return syncResolver.resolveSync(context, path, request);44};45const asyncContextResolver = ResolverFactory.createResolver({46 extensions: [".js", ".json", ".node"],47 resolveToContext: true,48 fileSystem: nodeFileSystem49});50module.exports.context = function resolveContext(context, path, request, resolveContext, callback) {51 if(typeof context === "string") {52 callback = resolveContext;53 resolveContext = request;54 request = path;55 path = context;56 context = nodeContext;57 }58 if(typeof callback !== "function") {59 callback = resolveContext;60 }61 asyncContextResolver.resolve(context, path, request, resolveContext, callback);62};63const syncContextResolver = ResolverFactory.createResolver({64 extensions: [".js", ".json", ".node"],65 resolveToContext: true,66 useSyncFileSystemCalls: true,67 fileSystem: nodeFileSystem68});69module.exports.context.sync = function resolveContextSync(context, path, request) {70 if(typeof context === "string") {71 request = path;72 path = context;73 context = nodeContext;74 }75 return syncContextResolver.resolveSync(context, path, request);76};77const asyncLoaderResolver = ResolverFactory.createResolver({78 extensions: [".js", ".json", ".node"],79 moduleExtensions: ["-loader"],80 mainFields: ["loader", "main"],81 fileSystem: nodeFileSystem82});83module.exports.loader = function resolveLoader(context, path, request, resolveContext, callback) {84 if(typeof context === "string") {85 callback = resolveContext;86 resolveContext = request;87 request = path;88 path = context;89 context = nodeContext;90 }91 if(typeof callback !== "function") {92 callback = resolveContext;93 }94 asyncLoaderResolver.resolve(context, path, request, resolveContext, callback);95};96const syncLoaderResolver = ResolverFactory.createResolver({97 extensions: [".js", ".json", ".node"],98 moduleExtensions: ["-loader"],99 mainFields: ["loader", "main"],100 useSyncFileSystemCalls: true,101 fileSystem: nodeFileSystem102});103module.exports.loader.sync = function resolveLoaderSync(context, path, request) {104 if(typeof context === "string") {105 request = path;106 path = context;107 context = nodeContext;108 }109 return syncLoaderResolver.resolveSync(context, path, request);110};111module.exports.create = function create(options) {112 options = Object.assign({113 fileSystem: nodeFileSystem114 }, options);115 const resolver = ResolverFactory.createResolver(options);116 return function(context, path, request, resolveContext, callback) {117 if(typeof context === "string") {118 callback = resolveContext;119 resolveContext = request;120 request = path;121 path = context;122 context = nodeContext;123 }124 if(typeof callback !== "function") {125 callback = resolveContext;126 }127 resolver.resolve(context, path, request, resolveContext, callback);128 };129};130module.exports.create.sync = function createSync(options) {131 options = Object.assign({132 useSyncFileSystemCalls: true,133 fileSystem: nodeFileSystem134 }, options);135 const resolver = ResolverFactory.createResolver(options);136 return function(context, path, request) {137 if(typeof context === "string") {138 request = path;139 path = context;140 context = nodeContext;141 }142 return resolver.resolveSync(context, path, request);143 };144};145// Export Resolver, FileSystems and Plugins146module.exports.ResolverFactory = ResolverFactory;147module.exports.NodeJsInputFileSystem = NodeJsInputFileSystem;...
Using AI Code Generation
1const fc = require('fast-check');2const { context } = require('fast-check/lib/check/arbitrary/ContextArbitrary');3const { nat } = require('fast-check/lib/check/arbitrary/NumericArbitrary');4const { stringOf } = require('fast-check/lib/check/arbitrary/StringArbitrary');5const { tuple } = require('fast-check/lib/check/arbitrary/TupleArbitrary');6const { generate } = fc;7const contextArb = context(tuple([nat(), stringOf(nat())]));8generate(contextArb, 1).forEach((value) => {9 console.log(value);10});11const fc = require('fast-check');12const { context } = require('fast-check/lib/check/arbitrary/ContextArbitrary');13const { nat } = require('fast-check/lib/check/arbitrary/NumericArbitrary');14const { stringOf } = require('fast-check/lib/check/arbitrary/StringArbitrary');15const { tuple } = require('fast-check/lib/check/arbitrary/TupleArbitrary');16const { generate } = fc;17const contextArb = context(tuple([nat(), stringOf(nat())]));18generate(contextArb, 1).forEach((value) => {19 console.log(value);20});
Using AI Code Generation
1const { context } = require('fast-check');2context().run(async () => {3 console.log('hello world');4});5const { context } = require('fast-check');6context().run(async () => {7 console.log('hello world');8});9const { context } = require('fast-check');10context().run(async () => {11 console.log('hello world');12});13const { context } = require('fast-check');14context().run(async () => {15 console.log('hello world');16});17const { context } = require('fast-check');18context().run(async () => {19 console.log('hello world');20});21const { context } = require('fast-check');22context().run(async () => {23 console.log('hello world');24});25const { context } = require('fast-check');26context().run(async () => {27 console.log('hello world');28});29const { context } = require('fast-check');30context().run(async () => {31 console.log('hello world');32});33const { context } = require('fast-check');34context().run(async () => {35 console.log('hello world');36});37const { context } = require('fast-check');38context().run(async () => {39 console.log('hello world');40});41const { context } = require('fast-check');42context().run(async () => {43 console.log('hello world');44});45const { context
Using AI Code Generation
1import { fc, testProp, testProp as testProp2 } from "fast-check";2testProp("test3", [fc.string()], () => {3 return true;4});5import { fc, testProp, testProp as testProp2 } from "fast-check";6testProp("test4", [fc.string()], () => {7 return true;8});9import { fc, testProp, testProp as testProp2 } from "fast-check";10testProp("test5", [fc.string()], () => {11 return true;12});13import { fc, testProp, testProp as testProp2 } from "fast-check";14testProp("test6", [fc.string()], () => {15 return true;16});17import { fc, testProp, testProp as testProp2 } from "fast-check";18testProp("test7", [fc.string()], () => {19 return true;20});21import { fc, testProp, testProp as testProp2 } from "fast-check";22testProp("test8", [fc.string()], () => {23 return true;24});25import { fc, testProp, testProp as testProp2 } from "fast-check";26testProp("test9", [fc.string()], () => {27 return true;28});29import { fc, testProp, testProp as testProp2 } from "fast-check";30testProp("test10", [fc.string()], () => {31 return true;32});33import { fc, testProp, testProp as testProp2 } from "fast-check";34testProp("test11", [fc.string()], () => {35 return true;36});
Using AI Code Generation
1import { fc } from 'fast-check';2import { context } from 'fast-check/lib/types/ContextArbitrary';3const contextArb = context(fc.integer(), fc.string());4fc.assert(5 fc.property(contextArb, (ctx) => {6 console.log(ctx);7 return true;8 })9);10{ counter: 0, seed: 0, path: '', endOnFailure: false }11{ counter: 1, seed: 0, path: '', endOnFailure: false }12{ counter: 2, seed: 0, path: '', endOnFailure: false }13{ counter: 3, seed: 0, path: '', endOnFailure: false }14{ counter: 4, seed: 0, path: '', endOnFailure: false }15{ counter: 5, seed: 0, path: '', endOnFailure: false }16{ counter: 6, seed: 0, path: '', endOnFailure: false }17{ counter: 7, seed: 0, path: '', endOnFailure: false }18{ counter: 8, seed: 0, path: '', endOnFailure: false }19{ counter: 9, seed: 0, path: '', endOnFailure: false }20import { fc } from 'fast-check';21import { context } from 'fast-check/lib/types/ContextArbitrary';22const contextArb = context(fc.integer(), fc.string());23fc.assert(24 fc.property(contextArb, (ctx) => {25 const arb = fc.array(fc.nat().map((n) => n * 3).filter((n) => n < ctx.counter));26 const out = fc.sample(arb, 100);27 return out.every((a) => a.length <= ctx.counter);28 })29);
Using AI Code Generation
1const fc = require('fast-check');2const ctx = fc.context();3const prop = fc.property(fc.integer({min: 0, max: 100}), fc.integer({min: 0, max: 100}), (a, b) => {4 ctx.log(`a: ${a} b: ${b}`);5 return a + b >= a && a + b >= b;6});7fc.assert(prop, {verbose: 1});
Using AI Code Generation
1const fc = require('fast-check');2const { context } = require('fast-check/lib/check/arbitrary/ContextArbitrary');3const randomString = () =>4 .stringOf(fc.char(), { minLength: 1, maxLength: 10 })5 .map((str) => str[0].toUpperCase() + str.slice(1));6const randomNumber = () =>7 fc.integer({ min: 1, max: 10 });8const randomObject = (keyArb, valueArb) =>9 fc.dictionary(keyArb, valueArb, { maxLength: 10 });10const randomArray = (valueArb) =>11 fc.array(valueArb, { maxLength: 10 });12const randomBoolean = () =>13 fc.boolean();14const randomDate = () =>15 fc.date();16const randomNull = () =>17 fc.constant(null);18const randomUndefined = () =>19 fc.constant(undefined);20const randomObject = (keyArb, valueArb) =>21 fc.dictionary(keyArb, valueArb, { maxLength: 10 });22const randomArray = (valueArb) =>23 fc.array(valueArb, { maxLength: 10 });24const randomBoolean = () =>25 fc.boolean();26const randomDate = () =>27 fc.date();28const randomNull = () =>29 fc.constant(null);30const randomUndefined = () =>31 fc.constant(undefined);32const randomObject = (keyArb, valueArb) =>33 fc.dictionary(keyArb, valueArb, { maxLength: 10 });34const randomArray = (valueArb) =>35 fc.array(valueArb, { maxLength: 10 });
Using AI Code Generation
1const fc = require('fast-check');2const { context } = require('fast-check');3context('test3', () => {4 it('should fail', () => {5 fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => {6 return a + b === a + b;7 }));8 });9});10const fc = require('fast-check');11const { context } = require('fast-check');12context('test4', () => {13 it('should fail', () => {14 fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => {15 return a + b === a + b;16 }));17 });18});19const fc = require('fast-check');20const { context } = require('fast-check');21context('test5', () => {22 it('should fail', () => {23 fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => {24 return a + b === a + b;25 }));26 });27});28const fc = require('fast-check');29const { context } = require('fast-check');30context('test6', () => {31 it('should fail', () => {32 fc.assert(fc.property(fc.integer(), fc.integer(), (a, b) => {33 return a + b === a + b;34 }));35 });36});37const fc = require('fast-check');38const { context } = require
Using AI Code Generation
1import { context } from 'fast-check-monorepo';2import { assert } from 'chai';3describe('test3', function() {4 it('test3', function() {5 const ctx = context();6 const fc = ctx.fastCheck;7 const assert = ctx.assert;8 fc.assert(9 fc.property(fc.integer(), fc.integer(), (a, b) => {10 assert.equal(a + b, b + a);11 })12 );13 });14});
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!