├── .babelrc
├── .eslintignore
├── .eslintrc
├── .gitignore
├── .npmignore
├── .travis.yml
├── CHANGELOG.md
├── CODE_OF_CONDUCT.md
├── IceDam.gif
├── LICENSE.md
├── README.md
├── examples
└── simple
│ ├── components
│ └── App.js
│ ├── index.html
│ ├── index.js
│ ├── package.json
│ ├── server.js
│ └── webpack.config.js
├── package.json
├── src
└── index.js
├── test
├── index.spec.js
├── mocha.opts
└── utils
│ └── document.js
└── webpack.config.js
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "stage": 0,
3 | "loose": "all"
4 | }
5 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | lib
2 | **/node_modules
3 | **/webpack.config.js
4 | examples/**/server.js
--------------------------------------------------------------------------------
/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "eslint-config-airbnb",
3 | "env": {
4 | "browser": true,
5 | "mocha": true,
6 | "node": true
7 | },
8 | "rules": {
9 | "react/jsx-uses-react": 2,
10 | "react/jsx-uses-vars": 2,
11 | "react/react-in-jsx-scope": 2,
12 |
13 |
14 | "func-names" : 0,
15 | "no-var" : 0,
16 | "one-var" : 0,
17 | "space-before-function-paren" : 0,
18 | "vars-on-top" : 0
19 | },
20 | "plugins": [
21 | "react"
22 | ]
23 | }
24 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | *.log
3 | .DS_Store
4 | dist
5 | lib
6 | coverage
7 | .idea
8 |
--------------------------------------------------------------------------------
/.npmignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | *.log
3 | src
4 | test
5 | examples
6 | coverage
7 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: node_js
2 | node_js:
3 | - "iojs"
4 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Change log
2 |
3 | All notable changes to this project will be documented in this file.
4 | This project adheres to [Semantic Versioning](http://semver.org/).
5 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Code of Conduct
2 |
3 | As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4 |
5 | We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion.
6 |
7 | Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8 |
9 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10 |
11 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12 |
13 | This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
14 |
15 |
--------------------------------------------------------------------------------
/IceDam.gif:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/winkler1/icedam/6010ef2cbf2e513dbfc9d68bc98a022f70a84ead/IceDam.gif
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2015 Jeff Winkler
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 | 
3 |
4 | Friends don't let friends mutate.
5 |
6 | ### What's This?
7 |
8 | Ice Dam: a very lightweight library to freeze data. Data is frozen at the __edge__, where your Flux container sends it to views.
9 |
10 | ### Why?
11 |
12 | To prevent accidental mutation and bugs.
13 |
14 | ### Show me the code!
15 | For Redux, you wrap a component in a `connect` function. Its first argument is a selector.
16 |
17 | ```
18 | function mapStateToProps(state) {
19 | return {
20 | products: state.products
21 | };
22 | }
23 |
24 | var App = connect(mapStateToProps)(App)
25 | ```
26 |
27 | Adding __freeze__ will call `Object.freeze` in development
28 |
29 | `npm install --save icedam`
30 |
31 | ```
32 | import {makeFreezer} from 'icedam';
33 | var freeze = makeFreezer();
34 |
35 | function mapStateToProps(state) {
36 | return freeze({
37 | products: state.products
38 | });
39 | }
40 |
41 | var App = connect(mapStateToProps)(App)
42 | ```
43 |
44 | ### Demos
45 |
46 | 
47 |
48 | [Screencast](https://www.youtube.com/watch?v=fPA_u4_iyK8)
49 |
50 | ### What about an library for immutability?
51 |
52 | Using an immutable library means commiting to using it throughout your stack. You'll have to change coding style, teach all your developers, and call `toJS()` when passing data. If your only concern is preventing views from mutating data, that might be too much.
53 |
54 | ### What about speed?
55 |
56 | In production: No cost. No freezing.
57 |
58 | In dev (`process.env.NODE_ENV === 'development'`): when data structures change, cloning has a slight cost, usually well under a millisecond.
59 |
60 | IceDam only clones objects when they have changed (!shallowEqual).
61 |
62 |
63 |
64 | Image Credit: [skekonk](https://www.flickr.com/photos/skedonk/4197921511/)
65 |
--------------------------------------------------------------------------------
/examples/simple/components/App.js:
--------------------------------------------------------------------------------
1 | import React, { Component } from 'react';
2 | import { add } from 'icedam';
3 |
4 | export default class App extends Component {
5 | render() {
6 | return (
7 |
8 | 2 + 2 = {add(2, 2)}
9 |
10 | );
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/examples/simple/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 | icedam-example-title
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/examples/simple/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import App from './components/App';
3 |
4 | React.render(
5 | ,
6 | document.getElementById('root')
7 | );
8 |
--------------------------------------------------------------------------------
/examples/simple/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "icedam-example",
3 | "version": "1.0.0",
4 | "description": "icedam-example-description",
5 | "main": "server.js",
6 | "scripts": {
7 | "start": "node server.js"
8 | },
9 | "repository": {
10 | "type": "git",
11 | "url": "https://github.com/winkler1/icedam.git"
12 | },
13 | "keywords": [
14 | "icedam-keywords"
15 | ],
16 | "license": "MIT",
17 | "bugs": {
18 | "url": "https://github.com/winkler1/icedam/issues"
19 | },
20 | "homepage": "https://github.com/winkler1/icedam",
21 | "dependencies": {
22 | "react": "^0.13.3"
23 | },
24 | "devDependencies": {
25 | "babel-core": "^5.6.18",
26 | "babel-loader": "^5.1.4",
27 | "node-libs-browser": "^0.5.2",
28 | "react-hot-loader": "^1.2.7",
29 | "webpack": "^1.9.11",
30 | "webpack-dev-server": "^1.9.0"
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/examples/simple/server.js:
--------------------------------------------------------------------------------
1 | var webpack = require('webpack');
2 | var WebpackDevServer = require('webpack-dev-server');
3 | var config = require('./webpack.config');
4 |
5 | new WebpackDevServer(webpack(config), {
6 | publicPath: config.output.publicPath,
7 | hot: true,
8 | historyApiFallback: true,
9 | stats: {
10 | colors: true
11 | }
12 | }).listen(3000, 'localhost', function (err) {
13 | if (err) {
14 | console.log(err);
15 | }
16 |
17 | console.log('Listening at localhost:3000');
18 | });
19 |
--------------------------------------------------------------------------------
/examples/simple/webpack.config.js:
--------------------------------------------------------------------------------
1 | var path = require('path');
2 | var webpack = require('webpack');
3 |
4 | module.exports = {
5 | devtool: 'eval',
6 | entry: [
7 | 'webpack-dev-server/client?http://localhost:3000',
8 | 'webpack/hot/only-dev-server',
9 | './index'
10 | ],
11 | output: {
12 | path: path.join(__dirname, 'dist'),
13 | filename: 'bundle.js',
14 | publicPath: '/static/'
15 | },
16 | plugins: [
17 | new webpack.HotModuleReplacementPlugin(),
18 | new webpack.NoErrorsPlugin()
19 | ],
20 | resolve: {
21 | alias: {
22 | 'icedam': path.join(__dirname, '..', '..', 'src')
23 | },
24 | extensions: ['', '.js']
25 | },
26 | module: {
27 | loaders: [{
28 | test: /\.js$/,
29 | loaders: ['react-hot', 'babel'],
30 | exclude: /node_modules/,
31 | include: __dirname
32 | }, {
33 | test: /\.js$/,
34 | loaders: ['babel'],
35 | include: path.join(__dirname, '..', '..', 'src')
36 | }]
37 | }
38 | };
39 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "icedam",
3 | "version": "0.0.2",
4 | "description": "Freezes data in development -- typically for Flux->React",
5 | "main": "lib/index.js",
6 | "scripts": {
7 | "clean": "rimraf lib dist",
8 | "build": "babel src --out-dir lib",
9 | "build:umd": "webpack src/index.js dist/icedam.js && NODE_ENV=production webpack src/index.js dist/icedam.min.js",
10 | "lint": "eslint src test examples",
11 | "test": "NODE_ENV=test mocha",
12 | "test:watch": "NODE_ENV=test mocha --watch",
13 | "test:cov": "babel-node ./node_modules/.bin/isparta cover ./node_modules/.bin/_mocha",
14 | "prepublish": "npm run lint && npm run test && npm run clean && npm run build && npm run build:umd"
15 | },
16 | "repository": {
17 | "type": "git",
18 | "url": "https://github.com/winkler1/icedam.git"
19 | },
20 | "keywords": [
21 | "immutable","reactjs","redux"
22 | ],
23 | "author": "Jeff Winkler",
24 | "license": "MIT",
25 | "bugs": {
26 | "url": "https://github.com/winkler1/icedam/issues"
27 | },
28 | "homepage": "https://github.com/winkler1/icedam",
29 | "devDependencies": {
30 | "babel": "^5.5.8",
31 | "babel-core": "^5.6.18",
32 | "babel-eslint": "^3.1.15",
33 | "babel-loader": "^5.1.4",
34 | "eslint": "^0.23",
35 | "eslint-config-airbnb": "0.0.6",
36 | "eslint-plugin-react": "^2.3.0",
37 | "expect": "^1.6.0",
38 | "invariant": "^2.0.0",
39 | "isparta": "^3.0.3",
40 | "mocha": "^2.2.5",
41 | "onchange": "^1.1.0",
42 | "rimraf": "^2.3.4",
43 | "webpack": "^1.9.6",
44 | "webpack-dev-server": "^1.8.2"
45 | },
46 | "dependencies": {
47 | "react-pure-render": "^1.0.2"
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | var makeFreezer;
2 |
3 | /* eslint no-inner-declarations:0 */
4 | if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
5 | const shallowEqual = require('react-pure-render/shallowEqual');
6 |
7 | function deepFreeze(obj) {
8 | Object.keys(obj).forEach(function (name) {
9 | const prop = obj[name];
10 | if (prop !== null && typeof prop === 'object' && !Object.isFrozen(prop)) {
11 | deepFreeze(prop);
12 | }
13 | });
14 | Object.freeze(obj);
15 | }
16 |
17 | function log() {
18 | // console.log(arguments);
19 | }
20 |
21 | // Make a freezer function that will cache its last results.
22 | makeFreezer = function (name = '') {
23 | var lastInput,
24 | lastOutput,
25 | totalSerializeTime = 0;
26 |
27 | return function (obj) {
28 | if (shallowEqual(lastInput, obj)) {
29 | log(`+1 cached ${name}`);
30 | return lastOutput;
31 | }
32 |
33 | // Clone and deep freeze the object.
34 | const startTime = new Date();
35 | lastInput = obj;
36 | lastOutput = JSON.parse(JSON.stringify(obj));
37 | const elapsed = new Date().getTime() - startTime.getTime();
38 | log(`FREEZE ${name}: freezing took ${elapsed}`);
39 | totalSerializeTime += elapsed;
40 | deepFreeze(lastOutput);
41 |
42 | return lastOutput;
43 | };
44 | };
45 | } else { // PRODUCTION.
46 |
47 | makeFreezer = function () {
48 | return function (obj) {
49 | return obj;
50 | };
51 | };
52 | }
53 |
54 | module.exports = {makeFreezer};
55 |
56 |
--------------------------------------------------------------------------------
/test/index.spec.js:
--------------------------------------------------------------------------------
1 | import expect from 'expect';
2 | import assert from 'assert';
3 | import {makeFreezer} from '../src';
4 |
5 |
6 | describe('Freezer', () => {
7 | var freeze;
8 | beforeEach(function () {
9 | freeze = makeFreezer();
10 | });
11 |
12 | it('Returns an equivalent, frozen array', function () {
13 | var input = [1, 2, 3];
14 | var output = freeze(input);
15 | expect(input).toNotBe(output);
16 | expect(input).toEqual(output);
17 | assert(Object.isFrozen(output));
18 | expect(()=> output.push(4)).toThrow(TypeError);
19 | expect(()=> output[0] = 99).toThrow(TypeError);
20 | expect(()=> output.pop()).toThrow(TypeError);
21 | expect(()=> output.reverse()).toThrow(TypeError);
22 | });
23 |
24 | it('Can freeze a big object', function () {
25 | // Array with 100K elements takes 4 ms to serialize and deserialize.
26 | var input = [];
27 | for (var x = 0; x < 10000; ++x) {
28 | input.push(x);
29 | }
30 | var output = freeze(input);
31 | expect(input).toNotBe(output);
32 | expect(input).toEqual(output);
33 | assert(Object.isFrozen(output));
34 | });
35 |
36 | it('Returns an equivalent, frozen object', function () {
37 | var input = {a: 1};
38 | var output = freeze(input);
39 | expect(input).toNotBe(output);
40 | expect(input).toEqual(output);
41 | assert(Object.isFrozen(output));
42 |
43 | expect(()=> output.a = 2).toThrow(TypeError);
44 | expect(()=> delete output.a).toThrow(TypeError);
45 | });
46 |
47 | it('Caches result', function () {
48 | var input = [1, 2, 3];
49 | var output1 = freeze(input);
50 | var output2 = freeze(input);
51 | expect(output1).toEqual(output2); // objects are equivalent
52 | assert(output1 === output2); // ...and same underlying objec.
53 | });
54 |
55 | it('Strips functions', function () {
56 | var input = {a: 1, fn: () => 1};
57 | var output = freeze(input);
58 |
59 | expect(Object.keys(output)).toEqual(['a']);
60 | });
61 |
62 | it('Handles null', function () {
63 | var input = {a: null};
64 | var output = freeze(input);
65 |
66 | expect(Object.keys(output)).toEqual(['a']);
67 | expect(output.a).toBe(null);
68 | });
69 |
70 | it('Removes non-enumerable properties', function () {
71 | var input = {};
72 | Object.defineProperties(input, {
73 | a: {enumerable: true, value: 'a'},
74 | b: {enumerable: false, value: 'b'}
75 | });
76 | var output = freeze(input);
77 | expect(Object.keys(output)).toEqual(['a']);
78 | });
79 |
80 | it('Handles nested objects', function () {
81 | var input = {
82 | person: {
83 | address: {
84 | street: '15 Main St',
85 | city: 'Boston',
86 | zip: {
87 | main: '12345',
88 | '+4': '6789'
89 | }
90 | },
91 | name: {
92 | first: 'Jacob',
93 | middle: 'Mr.',
94 | last: 'Winkler'
95 | }
96 | }
97 | };
98 | var output = freeze(input);
99 |
100 | expect(output.person.name.first).toEqual('Jacob');
101 | expect(input).toEqual(output);
102 | expect(input).toNotBe(output);
103 | });
104 | });
105 |
--------------------------------------------------------------------------------
/test/mocha.opts:
--------------------------------------------------------------------------------
1 | --compilers js:babel/register
2 | --recursive
3 |
--------------------------------------------------------------------------------
/test/utils/document.js:
--------------------------------------------------------------------------------
1 | if (typeof document === 'undefined') {
2 | global.document = {};
3 | }
4 |
--------------------------------------------------------------------------------
/webpack.config.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | var webpack = require('webpack');
4 |
5 | var plugins = [
6 | new webpack.optimize.OccurenceOrderPlugin()
7 | ];
8 |
9 | if (process.env.NODE_ENV === 'production') {
10 | plugins.push(
11 | new webpack.optimize.UglifyJsPlugin({
12 | compressor: {
13 | screw_ie8: true,
14 | warnings: false
15 | }
16 | })
17 | );
18 | }
19 |
20 | module.exports = {
21 | module: {
22 | loaders: [{
23 | test: /\.js$/,
24 | loaders: ['babel-loader'],
25 | exclude: /node_modules/
26 | }]
27 | },
28 | output: {
29 | library: 'icedam',
30 | libraryTarget: 'umd'
31 | },
32 | plugins: plugins,
33 | resolve: {
34 | extensions: ['', '.js']
35 | }
36 | };
37 |
--------------------------------------------------------------------------------