├── .nvmrc ├── .npmrc ├── .gitignore ├── tsconfig.json ├── .prettierrc ├── .huskyrc ├── commitlint.config.js ├── .npmignore ├── src ├── decorator.ts ├── decorator.spec.ts ├── types.ts ├── registry.ts ├── registry.spec.ts ├── index.ts └── index.spec.ts ├── jest.config.js ├── tslint.json ├── tsconfig.base.json ├── package.json ├── CHANGELOG.md ├── .circleci └── config.yml ├── README.md └── LICENSE /.nvmrc: -------------------------------------------------------------------------------- 1 | lts/dubnium 2 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | save-exact=true 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | dist 3 | node_modules 4 | coverage 5 | *.tgz 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.base.json", 3 | "exclude": ["**/*.spec.*", "dist/**/*"] 4 | } 5 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": false, 3 | "trailingComma": "all", 4 | "quoteProps": "consistent", 5 | "singleQuote": true 6 | } 7 | -------------------------------------------------------------------------------- /.huskyrc: -------------------------------------------------------------------------------- 1 | { 2 | "hooks": { 3 | "pre-commit": "pretty-quick --staged", 4 | "commit-msg": "commitlint -E HUSKY_GIT_PARAMS", 5 | "pre-push": "npm run lint" 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /commitlint.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ['@commitlint/config-conventional'], 3 | parserPreset: { 4 | parserOpts: { 5 | issuePrefixes: ['#'], 6 | }, 7 | }, 8 | } 9 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | coverage/ 3 | test/ 4 | build/ 5 | .idea/ 6 | .editorconfig 7 | .gitignore 8 | .huskyrc 9 | commitlint.config.js 10 | jest.config.js 11 | .nvmrc 12 | tsconfig.json 13 | tslint.json 14 | *.tgz 15 | .circleci/ 16 | -------------------------------------------------------------------------------- /src/decorator.ts: -------------------------------------------------------------------------------- 1 | import { createDecorator } from 'vue-class-component' 2 | 3 | // tslint:disable-next-line 4 | export const InjectModel = createDecorator((options: any, key) => { 5 | if (!options.injectModels) { 6 | options.injectModels = [] 7 | } 8 | options.injectModels.push(key) 9 | }) 10 | -------------------------------------------------------------------------------- /src/decorator.spec.ts: -------------------------------------------------------------------------------- 1 | import { InjectModel } from './decorator' 2 | import Component from 'vue-class-component' 3 | import Vue from 'vue' 4 | 5 | describe('InjectModel', () => { 6 | @Component 7 | class Test extends Vue { 8 | @InjectModel test: any 9 | } 10 | it('maps correctly', () => { 11 | const component = new Test() 12 | expect(component.$options.injectModels).toStrictEqual(['test']) 13 | }) 14 | }) 15 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | roots: ['/src'], 3 | transform: { 4 | '^.+\\.tsx?$': 'ts-jest', 5 | }, 6 | collectCoverage: true, 7 | testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$', 8 | moduleFileExtensions: ['js', 'ts'], 9 | coverageThreshold: { 10 | global: { 11 | branches: 90, 12 | functions: 90, 13 | lines: 90, 14 | statements: 90, 15 | }, 16 | }, 17 | } 18 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["tslint-config-airbnb", "tslint-config-prettier"], 3 | "rules": { 4 | "semicolon": [true, "never"], 5 | "import-name": [false], 6 | "object-shorthand-properties-first": [false], 7 | "ter-indent": [false], 8 | "max-line-length": [ 9 | true, 10 | { 11 | "limit": 120, 12 | "ignore-pattern": "^import |^export {(.*?)}|class [a-zA-Z]+ implements |// " 13 | } 14 | ] 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /tsconfig.base.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "dist/esm", 4 | "module": "es2015", 5 | "target": "es5", 6 | "lib": ["es2017", "es2016", "dom"], 7 | "sourceMap": true, 8 | "moduleResolution": "node", 9 | "noImplicitReturns": true, 10 | "noImplicitThis": true, 11 | "noImplicitAny": true, 12 | "strictNullChecks": true, 13 | "declaration": true, 14 | "esModuleInterop": true, 15 | "experimentalDecorators": true 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import { ComponentOptions } from 'vue/types/options' 2 | import { Vue, VueConstructor } from 'vue/types/vue' 3 | import Registry from './registry' 4 | 5 | declare module 'vue/types/options' { 6 | interface ComponentOptions { 7 | modelRegistry?: Registry 8 | injectModels?: string[] 9 | models?: VueModelMap | ((this: V) => VueModelMap) 10 | modelId?: string 11 | modelGId?: string 12 | exportState?: boolean | ((this: V, componentArgs: any) => boolean) 13 | } 14 | } 15 | 16 | declare module 'vue/types/vue' { 17 | // Global properties can be declared 18 | // on the `VueConstructor` interface 19 | interface Vue { 20 | $modelsProvidedKeys?: string[] 21 | $modelsProvided: { [key: string]: Vue } 22 | $modelRegistry: Registry 23 | } 24 | } 25 | 26 | export interface VueModelMap { 27 | [key: string]: ComponentOptions | VueConstructor 28 | } 29 | 30 | export interface ModelInstallOptions { 31 | mixins: Required>['mixins'] 32 | restoreOnReplace: boolean 33 | globalModels: { 34 | [key: string]: ComponentOptions 35 | } 36 | } 37 | 38 | export interface Export { 39 | [key: string]: string 40 | } 41 | -------------------------------------------------------------------------------- /src/registry.ts: -------------------------------------------------------------------------------- 1 | import { Vue } from 'vue/types/vue' 2 | import { Export } from './types' 3 | 4 | export interface ExportStateOptions { 5 | filterDefault?: boolean 6 | context?: any 7 | } 8 | 9 | /** 10 | * root registry of history and models, 11 | * to be registered on the Vue prototype 12 | */ 13 | export default class Registry { 14 | public models: { [key: string]: Vue } = {} 15 | private hydrationData: { [key: string]: () => object } = {} 16 | 17 | constructor(private readonly restoreOnReplace: boolean) {} 18 | 19 | register(vm: Vue) { 20 | const current = this.models[vm.$options.modelGId!] 21 | this.models[vm.$options.modelGId!] = vm 22 | if (current && this.restoreOnReplace) { 23 | Object.entries(current.$data).forEach(([key, value]) => { 24 | if (vm.$data.hasOwnProperty(key)) { 25 | vm.$set(vm.$data, key, value) 26 | } 27 | }) 28 | } 29 | } 30 | 31 | unregister(vm: Vue) { 32 | if (this.models[vm.$options.modelGId!] === vm) { 33 | delete this.models[vm.$options.modelGId!] 34 | } 35 | } 36 | 37 | exportState({ 38 | filterDefault = true, 39 | context, 40 | }: ExportStateOptions = {}): Export { 41 | const mapped: Export = {} 42 | 43 | Object.entries(this.models) 44 | .filter(([_, vm]) => { 45 | const { exportState } = vm.$options 46 | if (typeof exportState === 'undefined') { 47 | return filterDefault 48 | } 49 | if (typeof exportState === 'function') { 50 | return exportState.call(vm, context) 51 | } 52 | return exportState 53 | }) 54 | .forEach(([key, vm]) => { 55 | mapped[key] = JSON.stringify(Object.assign({}, vm.$data)) 56 | }) 57 | 58 | return mapped 59 | } 60 | 61 | importState(hydrModels: Export) { 62 | Object.keys(hydrModels).forEach(key => { 63 | this.hydrationData[key] = () => JSON.parse(hydrModels[key]) 64 | }) 65 | } 66 | 67 | getImportedStateFor(modelGId: string): (() => object) | undefined { 68 | const data = this.hydrationData[modelGId] 69 | delete this.hydrationData[modelGId] 70 | return data 71 | } 72 | } 73 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@sum.cumo/vue-states", 3 | "version": "1.3.2", 4 | "description": "Component-based Vue.js state management", 5 | "main": "dist/vue-states.umd.js", 6 | "module": "dist/vue-states.esm.js", 7 | "unpkg": "dist/vue-states.min.js", 8 | "types": "dist/index.d.ts", 9 | "keywords": [ 10 | "vue", 11 | "vuex", 12 | "state", 13 | "management", 14 | "mvc", 15 | "model", 16 | "controller" 17 | ], 18 | "repository": { 19 | "type": "git", 20 | "url": "git@github.com:sumcumo/vue-states.git" 21 | }, 22 | "homepage": "https://github.com/sumcumo/vue-states", 23 | "scripts": { 24 | "test": "jest --coverage=false", 25 | "test.coverage": "jest", 26 | "release": "git checkout master && git pull origin master && standard-version", 27 | "lint": "tslint -p ./tsconfig.base.json", 28 | "build": "npm run build:clear && npm run build:browser && npm run build:es && npm run build:umd", 29 | "build:clear": "rm -rf ./dist", 30 | "build:browser": "rollup --config build/rollup.config.browser.js", 31 | "build:es": "rollup --config build/rollup.config.es.js", 32 | "build:umd": "rollup --config build/rollup.config.umd.js", 33 | "prepack": "npm run test.coverage && npm run lint && npm run build" 34 | }, 35 | "author": "sum.cumo GmbH", 36 | "license": "Apache-2.0", 37 | "dependencies": { 38 | "vue-class-component": "^7.2.6" 39 | }, 40 | "devDependencies": { 41 | "@commitlint/cli": "11.0.0", 42 | "@commitlint/config-conventional": "11.0.0", 43 | "@types/jest": "26.0.20", 44 | "@vue/test-utils": "1.1.2", 45 | "husky": "4.3.8", 46 | "jest": "26.6.3", 47 | "prettier": "2.2.1", 48 | "pretty-quick": "3.1.0", 49 | "rollup": "2.36.1", 50 | "rollup-plugin-terser": "7.0.2", 51 | "rollup-plugin-typescript2": "0.29.0", 52 | "standard-version": "9.1.0", 53 | "ts-jest": "26.5.0", 54 | "tslib": "2.1.0", 55 | "tslint": "6.1.3", 56 | "tslint-config-airbnb": "5.11.2", 57 | "tslint-config-prettier": "1.18.0", 58 | "typescript": "4.1.3", 59 | "vue": "2.6.12", 60 | "vue-template-compiler": "2.6.12" 61 | }, 62 | "peerDependencies": { 63 | "vue": ">=2.5.0" 64 | }, 65 | "contributors": [ 66 | "Steffan Schiewe (https://github.com/steffans)" 67 | ] 68 | } 69 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. 4 | 5 | ### [1.3.2](https://github.com/sumcumo/vue-states/compare/v1.3.1...v1.3.2) (2019-09-05) 6 | 7 | 8 | ### Bug Fixes 9 | 10 | * vue-class-component as dependency ([2a23a2c](https://github.com/sumcumo/vue-states/commit/2a23a2c)) 11 | 12 | ### [1.3.1](https://github.com/sumcumo/vue-states/compare/v1.3.0...v1.3.1) (2019-09-05) 13 | 14 | 15 | ### Bug Fixes 16 | 17 | * rollup setup ([7b3fc6c](https://github.com/sumcumo/vue-states/commit/7b3fc6c)) 18 | 19 | ## [1.3.0](https://github.com/sumcumo/vue-states/compare/v1.2.0...v1.3.0) (2019-09-05) 20 | 21 | 22 | ### Bug Fixes 23 | 24 | * refine ComponentOption type ([d4a6ee7](https://github.com/sumcumo/vue-states/commit/d4a6ee7)) 25 | 26 | 27 | ### Features 28 | 29 | * add InjectModel decorator ([0955551](https://github.com/sumcumo/vue-states/commit/0955551)) 30 | 31 | ## [1.2.0](https://github.com/sumcumo/vue-states/compare/v1.1.0...v1.2.0) (2019-08-15) 32 | 33 | 34 | ### Features 35 | 36 | * support filtering state export ([b73c4a2](https://github.com/sumcumo/vue-states/commit/b73c4a2)), closes [#27](https://github.com/sumcumo/vue-states/issues/27) 37 | 38 | 39 | # [1.1.0](https://github.com/sumcumo/vue-states/compare/v1.0.3...v1.1.0) (2019-05-09) 40 | 41 | 42 | ### Bug Fixes 43 | 44 | * set correct reference to "types" in package.json ([bf340c8](https://github.com/sumcumo/vue-states/commit/bf340c8)) 45 | 46 | 47 | ### Features 48 | 49 | * extend type-declaration of vue component options ([8fc7fe1](https://github.com/sumcumo/vue-states/commit/8fc7fe1)) 50 | * extend Vue interface type and simplify internal type definitions ([5b2124b](https://github.com/sumcumo/vue-states/commit/5b2124b)) 51 | * implement support for vue subclasses as models ([392b57d](https://github.com/sumcumo/vue-states/commit/392b57d)) 52 | 53 | 54 | 55 | 56 | ## [1.0.3](https://github.com/sumcumo/vue-states/compare/v1.0.2...v1.0.3) (2019-04-17) 57 | 58 | * docs: add example link to README.md 59 | 60 | 61 | 62 | ## [1.0.2](https://github.com/sumcumo/vue-states/compare/v1.0.1...v1.0.2) (2019-04-10) 63 | 64 | * The plugin was renamed from Vue Models to Vue States. 65 | 66 | 67 | 68 | ## [1.0.1](https://github.com/sumcumo/vue-states/compare/v1.0.0...v1.0.1) (2019-04-08) 69 | 70 | 71 | ### Bug Fixes 72 | 73 | * lint spec files excluded by tsconfig ([e938d11](https://github.com/sumcumo/vue-states/commit/e938d11)) 74 | 75 | 76 | 77 | 78 | # 1.0.0 (2019-04-05) 79 | -------------------------------------------------------------------------------- /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | 3 | defaults: &defaults 4 | working_directory: ~/repo 5 | docker: 6 | - image: circleci/node:lts 7 | 8 | jobs: 9 | checkout-code: 10 | <<: *defaults 11 | steps: 12 | - checkout 13 | - persist_to_workspace: 14 | root: ~/repo 15 | paths: 16 | - ./ 17 | - save_cache: 18 | key: v1-repo-{{ .Environment.CIRCLE_SHA1 }} 19 | paths: 20 | - ~/repo 21 | 22 | npm: 23 | <<: *defaults 24 | steps: 25 | - attach_workspace: 26 | at: ~/repo 27 | - restore_cache: 28 | keys: 29 | - v1-npm-{{ checksum "package-lock.json" }} 30 | - v1-npm- 31 | - run: 32 | name: Install 33 | command: npm ci 34 | - persist_to_workspace: 35 | root: ~/repo 36 | paths: 37 | - node_modules 38 | - save_cache: 39 | key: v1-npm-{{ checksum "package-lock.json" }} 40 | paths: 41 | - ~/repo/node_modules 42 | 43 | audit: 44 | <<: *defaults 45 | steps: 46 | - attach_workspace: 47 | at: ~/repo 48 | - run: 49 | name: Audit 50 | command: npm audit 51 | 52 | lint: 53 | <<: *defaults 54 | steps: 55 | - attach_workspace: 56 | at: ~/repo 57 | - run: 58 | name: Lint 59 | command: npm run lint 60 | 61 | test: 62 | <<: *defaults 63 | steps: 64 | - attach_workspace: 65 | at: ~/repo 66 | - run: 67 | name: Setup Code Climate test-reporter 68 | command: | 69 | # download test reporter as a static binary 70 | curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter 71 | chmod +x ./cc-test-reporter 72 | - run: 73 | name: Run tests 74 | command: | 75 | # notify Code Climate of a pending test report using `before-build` 76 | ./cc-test-reporter before-build 77 | npm run test.coverage 78 | # upload test report to Code Climate using `after-build` 79 | ./cc-test-reporter after-build --coverage-input-type lcov --exit-code $? 80 | 81 | build: 82 | <<: *defaults 83 | steps: 84 | - attach_workspace: 85 | at: ~/repo 86 | - run: 87 | name: Build from source 88 | command: npm run build 89 | 90 | workflows: 91 | version: 2 92 | check: 93 | triggers: 94 | - schedule: 95 | cron: '0 20 * * *' 96 | filters: 97 | branches: 98 | only: master 99 | jobs: 100 | - checkout-code 101 | - npm: 102 | requires: 103 | - checkout-code 104 | - audit: 105 | requires: 106 | - npm 107 | 108 | main: 109 | jobs: 110 | - checkout-code 111 | - npm: 112 | requires: 113 | - checkout-code 114 | - audit: 115 | requires: 116 | - npm 117 | - lint: 118 | requires: 119 | - npm 120 | - test: 121 | requires: 122 | - npm 123 | - build: 124 | requires: 125 | - lint 126 | - audit 127 | -------------------------------------------------------------------------------- /src/registry.spec.ts: -------------------------------------------------------------------------------- 1 | import { createLocalVue, mount } from '@vue/test-utils' 2 | import { ComponentOptions } from 'vue' 3 | import { Vue } from 'vue/types/vue' 4 | import VueStates from './index' 5 | import { ExportStateOptions } from './registry' 6 | 7 | const localVue = createLocalVue() 8 | localVue.use(VueStates) 9 | 10 | /* tslint:disable-next-line:variable-name */ 11 | const createModel = (value: string) => ({ 12 | data() { 13 | return { 14 | key: value, 15 | } 16 | }, 17 | }) 18 | 19 | function createWrapper(exportState?: ComponentOptions['exportState']) { 20 | return mount( 21 | { 22 | models: { 23 | one: { 24 | ...createModel('one'), 25 | exportState, 26 | }, 27 | }, 28 | render(h) { 29 | return h('div') 30 | }, 31 | }, 32 | { localVue }, 33 | ) 34 | } 35 | 36 | function exportFromWrapper( 37 | exportState?: ComponentOptions['exportState'], 38 | options?: ExportStateOptions, 39 | ) { 40 | const wrapper = createWrapper(exportState) 41 | return wrapper.vm.$modelRegistry.exportState(options) 42 | } 43 | 44 | const standardExportedState = { 45 | 'one~single': JSON.stringify({ key: 'one' }), 46 | } 47 | 48 | describe('registry', () => { 49 | it('should export state', () => { 50 | const wrapper = mount( 51 | { 52 | models: { 53 | one: createModel('one'), 54 | two: createModel('two'), 55 | }, 56 | render(h) { 57 | return h('div') 58 | }, 59 | }, 60 | { localVue }, 61 | ) 62 | const exported = wrapper.vm.$modelRegistry.exportState() 63 | expect(exported).toEqual({ 64 | 'one~single': JSON.stringify({ key: 'one' }), 65 | 'two~single': JSON.stringify({ key: 'two' }), 66 | }) 67 | }) 68 | 69 | it('should filter exportState on boolean', () => { 70 | expect(exportFromWrapper(false)).toEqual({}) 71 | expect(exportFromWrapper(true)).toEqual(standardExportedState) 72 | }) 73 | 74 | it('should filter exportState on callback', () => { 75 | expect( 76 | exportFromWrapper(function() { 77 | // @ts-ignore 78 | return this.key === 'one' 79 | }), 80 | ).toEqual(standardExportedState) 81 | expect( 82 | exportFromWrapper(function() { 83 | // @ts-ignore 84 | return this.key !== 'one' 85 | }), 86 | ).toEqual({}) 87 | }) 88 | 89 | it('should forward args to callback', () => { 90 | let shouldExport = true 91 | 92 | const exportStateCallback = jest.fn(({ shouldExport }) => shouldExport) 93 | 94 | function exportWithContext() { 95 | return exportFromWrapper(exportStateCallback, { 96 | context: { shouldExport }, 97 | }) 98 | } 99 | 100 | expect(exportWithContext()).toEqual(standardExportedState) 101 | expect(exportStateCallback).toHaveBeenLastCalledWith({ shouldExport }) 102 | 103 | shouldExport = false 104 | 105 | expect(exportWithContext()).toEqual({}) 106 | expect(exportStateCallback).toHaveBeenLastCalledWith({ shouldExport }) 107 | }) 108 | 109 | it('should use default when exportState is undefined', () => { 110 | expect(exportFromWrapper()).toEqual(standardExportedState) 111 | expect(exportFromWrapper(undefined, { filterDefault: false })).toEqual({}) 112 | }) 113 | }) 114 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { ComponentOptions, VueConstructor } from 'vue' 2 | import { Vue } from 'vue/types/vue' 3 | import Registry from './registry' 4 | import { ModelInstallOptions } from './types' 5 | 6 | export * from './decorator' 7 | export { Registry } 8 | 9 | interface InstallContext { 10 | vue: VueConstructor 11 | installOptions: ModelInstallOptions 12 | } 13 | 14 | function resolveInjection(this: Vue, key: string) { 15 | // tslint:disable-next-line no-this-assignment 16 | let source = this 17 | let ressource: Vue | null = null 18 | 19 | while ((source = source.$parent)) { 20 | if ( 21 | source.$modelsProvidedKeys && 22 | source.$modelsProvidedKeys.includes(key) 23 | ) { 24 | ressource = source 25 | break 26 | } 27 | } 28 | 29 | if (ressource === null) { 30 | throw new Error(`No provider found for ${key}`) 31 | } 32 | 33 | Object.defineProperty(this, key, { 34 | get: () => (ressource as any)[key], 35 | }) 36 | } 37 | 38 | function createModelOptions( 39 | vmHost: Vue, 40 | name: string, 41 | options: ComponentOptions, 42 | mergeMixins: Required>['mixins'], 43 | ): ComponentOptions { 44 | const modelId = options.modelId || 'single' 45 | const modelGId = `${name}~${modelId}` 46 | const data = 47 | vmHost.$modelRegistry.getImportedStateFor(modelGId) || 48 | options.data || 49 | (() => ({})) 50 | const mixins = [...mergeMixins, ...(options.mixins || [])] 51 | 52 | return Object.assign({}, options, { 53 | mixins, 54 | name, 55 | modelId, 56 | modelGId, 57 | data, 58 | parent: vmHost, 59 | }) 60 | } 61 | 62 | const OPTIONS_DEFAULTS: ModelInstallOptions = { 63 | mixins: [], 64 | restoreOnReplace: false, 65 | globalModels: {}, 66 | } 67 | 68 | function createModel( 69 | this: Vue, 70 | context: InstallContext, 71 | key: string, 72 | optionsOrClass: ComponentOptions | VueConstructor, 73 | ) { 74 | const isClass = 75 | typeof optionsOrClass === 'function' && 76 | // check for 'super' to enable later support for options like 77 | // models: { Content: () => import('some-chunk') } 78 | typeof (optionsOrClass as any).super === 'function' 79 | 80 | const options = createModelOptions( 81 | this, 82 | key, 83 | isClass ? {} : (optionsOrClass as ComponentOptions), 84 | context.installOptions.mixins, 85 | ) 86 | const vm = new (isClass ? (optionsOrClass as VueConstructor) : context.vue)( 87 | options, 88 | ) 89 | ;(this as any)[key] = this.$modelsProvided[key] = vm 90 | this.$modelRegistry.register(vm) 91 | 92 | this.$on('hook:beforeDestroy', () => { 93 | this.$modelRegistry.unregister(vm) 94 | vm.$destroy() 95 | }) 96 | } 97 | 98 | function createModels(this: Vue, context: InstallContext) { 99 | this.$modelsProvided = {} 100 | 101 | if (!this.$options.models && this !== this.$root) { 102 | return 103 | } 104 | 105 | let { models = {} } = this.$options 106 | 107 | if (typeof models === 'function') { 108 | models = models.call(this) 109 | } 110 | 111 | if (this === this.$root) { 112 | const globalModels = context.installOptions.globalModels 113 | Object.values(globalModels).forEach(m => (m.modelId = 'global')) 114 | models = Object.assign({}, globalModels, models) 115 | } 116 | 117 | this.$modelsProvidedKeys = Object.keys(models) 118 | 119 | Object.entries(models).forEach(([key, options]) => { 120 | createModel.call(this, context, key, options) 121 | }) 122 | } 123 | 124 | export default { 125 | install( 126 | vue: VueConstructor, 127 | rawInstallOptions: Partial = {}, 128 | ) { 129 | const installOptions: ModelInstallOptions = Object.assign( 130 | {}, 131 | OPTIONS_DEFAULTS, 132 | rawInstallOptions, 133 | ) 134 | 135 | vue.mixin({ 136 | beforeCreate(this: Vue) { 137 | const { modelRegistry, injectModels } = this.$options 138 | this.$modelRegistry = 139 | this === this.$root 140 | ? modelRegistry || new Registry(installOptions.restoreOnReplace) 141 | : this.$root.$modelRegistry 142 | 143 | if (injectModels) { 144 | injectModels.forEach(inject => { 145 | resolveInjection.call(this, inject) 146 | }) 147 | } 148 | }, 149 | created(this: Vue) { 150 | createModels.call(this, { vue, installOptions }) 151 | }, 152 | }) 153 | }, 154 | } 155 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![CircleCI](https://circleci.com/gh/sumcumo/vue-states.svg?style=svg)](https://circleci.com/gh/sumcumo/vue-states) 2 | [![Maintainability](https://api.codeclimate.com/v1/badges/635869dc6220b29b1aa6/maintainability)](https://codeclimate.com/github/sumcumo/vue-states/maintainability) 3 | [![Test Coverage](https://api.codeclimate.com/v1/badges/635869dc6220b29b1aa6/test_coverage)](https://codeclimate.com/github/sumcumo/vue-states/test_coverage) 4 | 5 | # Vue States 6 | 7 | _Vue States is a state management system for Vue.js._ 8 | 9 | Checkout the examples at https://github.com/JohannesLamberts/vue-states-examples. 10 | 11 | You might want to choose to use Vue States for: 12 | 13 | - **Simplicity**
Just `this.MyModel.key` and `this.MyModel.update(payload)`. No huge API, that exposes implementation details like `state, getters, commit, dispatch`.
Hot Module Replacement and Lazy-Loading made easy. 14 | - **Flexible scope**
It is designed to support application-wide and local state, and can still be hydrated from SSR or localStorage. 15 | - **Learning & refactoring**
The state is composed of Vue components. That means: almost no new APIs and patterns to learn, plus seamless refactoring of your application. 16 | - **Power**
All plugins and native Vue capabilities are accessible by design, without any configuration ( `this.$router, this.$apollo, created()...` ). 17 | - **[History](#history)**
In combination with [Vue History](https://github.com/sumcumo/vue-history) you get a detailed view of what's going on, even for complex scenarios, async processes, error tracking and deeply nested call chains. 18 | 19 | _This package was released just recently. Feedback is highly welcome._ 20 | 21 | ## Installation 22 | 23 | The plugin can be installed without any further options: 24 | 25 | ```javascript 26 | import VueStates from '@sum.cumo/vue-states' 27 | Vue.use(VueStates) 28 | ``` 29 | 30 | ...or with additional configuration: 31 | 32 | ```javascript 33 | Vue.use(VueStates, { 34 | // equal to Vue mixins, will be applied to every created model 35 | mixins: [], 36 | 37 | // a models state will be restored 38 | // if an old match (same name and modelId) is found 39 | // can be used to preserve state during hot module replacement 🚀 40 | // default: false 41 | restoreOnReplace: process.env.NODE_ENV === 'development', 42 | 43 | // registers models on the $root instance, same as 44 | // const app = new Vue({ models: globalModels }) 45 | globalModels, 46 | }) 47 | ``` 48 | 49 | ## Getting started 50 | 51 | ### Declare 52 | 53 | A model is declared like any other vue-component, only that it doesn't contain any template or render option. 54 | 55 | ```javascript 56 | import productsGQL from '@/api/queries/fakeProducts.graphql' 57 | 58 | export default { 59 | data() { 60 | return { 61 | stage: '', 62 | products: [], 63 | } 64 | }, 65 | 66 | // created / destroy hooks are invoked 67 | created() { 68 | this.stage = 'created' 69 | this.loadProducts() 70 | }, 71 | 72 | // vuex mutations and actions become just methods 73 | methods: { 74 | async loadProducts() { 75 | this.saveProducts(await this.$api.loadProducts()) 76 | }, 77 | saveProducts(products) { 78 | this.products = products 79 | }, 80 | }, 81 | 82 | // vuex getters become computed 83 | computed: { 84 | stageUppercase() { 85 | return this.stage.toUpperCase() 86 | }, 87 | }, 88 | } 89 | ``` 90 | 91 | ### Hosting 92 | 93 | A model is a renderless component that is provided by a hosting component. 94 | It is available in the hosting component itself and any child component, that injects the model. 95 | 96 | ```javascript 97 | import App from '@/models/example' 98 | 99 | export default { 100 | name: 'ExampleHost', 101 | 102 | models: { 103 | // 'App' becomes the models name and the key to reference it 104 | App, 105 | }, 106 | 107 | template: ` 108 |
109 | 113 | {{ App.stageUppercase }} 114 | 115 |
`, 116 | } 117 | ``` 118 | 119 | ### Injection 120 | 121 | ```javascript 122 | export default { 123 | name: 'ExampleChild', 124 | 125 | injectModels: ['App'], 126 | 127 | template: ` 128 |
129 | 130 | {{App.products.length}} 131 | 132 |
`, 134 | } 135 | ``` 136 | 137 | ## History 138 | 139 | To keep track of what happens inside the models can check out [Vue History](https://github.com/sumcumo/vue-history), 140 | a package that was developed alongside Vue States but not only works for models but for any Vue component. 141 | 142 | After installing Vue History you can enable it for all models by setting the `history: true` option: 143 | 144 | ```javascript 145 | import VueHistory from '@sum.cumo/vue-history' 146 | import VueStates from '@sum.cumo/vue-states' 147 | 148 | Vue.use(VueHistory) 149 | 150 | Vue.use(VueStates, { mixins: [{ history: true }] }) 151 | ``` 152 | 153 | ## State export/import 154 | 155 | State can be exported from and imported into the root model registry. 156 | The imported state will be used when initializing models with matching name and modelId. 157 | The state must therefore be imported _before_ the model is initialized. 158 | 159 | ```javascript 160 | const exported = app.$modelRegistry.exportState() 161 | app.$modelRegistry.importState(exported) 162 | ``` 163 | 164 | Using export/import you can persist state to localStorage or initialize state before Client Side Hydration after SSR. 165 | 166 | ### Filtered Export 167 | 168 | The export can be configured to filter which models will be included in the export. 169 | 170 | ```javascript 171 | const exported = app.$modelRegistry.exportState({ 172 | // default: true, 173 | // set to false to exclude all models, 174 | // where `exportState` is undefined 175 | filterDefault: false, 176 | 177 | // context will be passed to exportState callbacks 178 | context: { 179 | isLocalStorageExport: true, 180 | }, 181 | }) 182 | ``` 183 | 184 | Models may include an `exportState` option, which must be 185 | either a function or a boolean. 186 | 187 | ``` 188 | export default { 189 | name: 'UserModel', 190 | exportState(context) { 191 | return context.isLocalStorageExport 192 | // vm can be accessed from withing the callback 193 | && this.isLoggedIn 194 | } 195 | } 196 | ``` 197 | 198 | ``` 199 | export default { 200 | name: 'SomeOtherModel' 201 | exportState: false, 202 | } 203 | ``` 204 | 205 | ### Server Side Rendering 206 | 207 | ```javascript 208 | // entry-server.js 209 | Object.defineProperty(context, 'vueModelState', { 210 | get: () => { 211 | return app.$modelRegistry.exportState() 212 | }, 213 | }) 214 | ``` 215 | 216 | ```html 217 | 218 | {{{ renderState({ contextKey: 'vueModelState', windowKey: '__VUE_STATES__' }) 219 | }}} 220 | ``` 221 | 222 | ```javascript 223 | // main.js 224 | import { Registry } from '@sum.cumo/vue-states' 225 | 226 | export default async function createApp() { 227 | // ... 228 | 229 | const modelRegistry = new Registry() 230 | 231 | if (typeof window !== 'undefined' && window.__VUE_STATES__) { 232 | modelRegistry.importState(window.__VUE_STATES__) 233 | } 234 | 235 | const app = new Vue({ 236 | // you only need to provide this option if you need to import an initial state 237 | // the registry will be automatically initialized otherwise 238 | modelRegistry, 239 | // ... 240 | }) 241 | } 242 | ``` 243 | 244 | ### Multi-Instances 245 | 246 | When using models for non application-wide state you might have multiple instances of the same model running concurrently. 247 | For import/export to work you will need to provide an id to further identify the different models. 248 | 249 | ```javascript 250 | export default modelId => ({ 251 | // the combination of name and modelId must be unique at any given time 252 | modelId, 253 | 254 | data() { 255 | return { 256 | counter: 0, 257 | } 258 | }, 259 | 260 | methods: { 261 | increment() { 262 | this.counter += 1 263 | }, 264 | }, 265 | }) 266 | ``` 267 | 268 | ```javascript 269 | import createCounter from '@/models/counter' 270 | 271 | export default { 272 | props: { 273 | someIdentifier: { 274 | type: String, 275 | required: true, 276 | }, 277 | }, 278 | 279 | // you may also pass a function that is evaluated in the created hook 280 | // and receives the hosting Vue component as context 281 | models() { 282 | return { 283 | Counter: createCounter(this.someIdentifier), 284 | } 285 | }, 286 | } 287 | ``` 288 | 289 | ## Nuxt.js 290 | 291 | Nuxt.js gets confused by the models attached to the component tree. The errors can be resolved by adding `abtract: true` to all models (which however makes them invisible in the developer tools). 292 | 293 | ```javascript 294 | Vue.use(VueStates, { mixins: [{ abstract: true }] }) 295 | ``` 296 | 297 | ## License 298 | 299 | Copyright 2019 [sum.cumo GmbH](https://www.sumcumo.com/) 300 | 301 | Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at 302 | 303 | http://www.apache.org/licenses/LICENSE-2.0 304 | 305 | Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. 306 | 307 | --- 308 | 309 | [Learn more about sum.cumo](https://www.sumcumo.com/en) and [work on open source projects](https://www.sumcumo.com/jobs), too! 310 | -------------------------------------------------------------------------------- /src/index.spec.ts: -------------------------------------------------------------------------------- 1 | import { createLocalVue, mount } from '@vue/test-utils' 2 | import Vue from 'vue' 3 | import Component from 'vue-class-component' 4 | import VueStates from './index' 5 | import Registry from './registry' 6 | 7 | /* tslint:disable-next-line:variable-name */ 8 | const GlobalModel = { 9 | data() { 10 | return { 11 | globalData: true, 12 | } 13 | }, 14 | } 15 | 16 | const localVue = createLocalVue() 17 | localVue.use(VueStates) 18 | 19 | /* tslint:disable-next-line:variable-name */ 20 | const SomeModel = { 21 | modelId: 'someId', 22 | data() { 23 | return { 24 | foo: 'bar', 25 | } 26 | }, 27 | } 28 | 29 | /* tslint:disable-next-line:variable-name */ 30 | const SomeSingleModel = { 31 | data() { 32 | return { 33 | singleFoo: 'singleBar', 34 | } 35 | }, 36 | } 37 | 38 | /* tslint:disable-next-line:variable-name */ 39 | const SomeStatelessModel = { 40 | methods: { 41 | ping() { 42 | return 'pong' 43 | }, 44 | }, 45 | } 46 | 47 | const models = { 48 | SomeModel, 49 | SomeSingleModel, 50 | SomeStatelessModel, 51 | } 52 | 53 | const provideComponent = (renderedComponent: any) => 54 | ({ 55 | name: 'ProviderComponent', 56 | models, 57 | render(h: any) { 58 | return h(renderedComponent) 59 | }, 60 | } as any) 61 | 62 | const consumerComponent = { 63 | name: 'ConsumerComponent', 64 | injectModels: ['SomeModel'], 65 | render(this: any, h: any) { 66 | return h('div', { domProps: { id: 'fooContainer' } }, this.SomeModel.foo) 67 | }, 68 | } 69 | 70 | describe('Vue States', () => { 71 | let wrapper: any 72 | 73 | let mockError: jest.Mock 74 | let storedError: any 75 | 76 | beforeEach(() => { 77 | const c = provideComponent(consumerComponent) 78 | wrapper = mount(c, { localVue }) 79 | mockError = jest.fn() 80 | storedError = global.console.error 81 | global.console.error = mockError 82 | }) 83 | 84 | afterEach(() => { 85 | global.console.error = storedError 86 | }) 87 | 88 | // adding elements to $root seems to be incompatible with mount() 89 | it('should add globalModels to the root component', () => { 90 | const globalModelsVue = createLocalVue() 91 | globalModelsVue.use(VueStates, { 92 | globalModels: { 93 | GlobalModel, 94 | }, 95 | }) 96 | 97 | const model = new globalModelsVue() as any 98 | expect(model.GlobalModel).toBeInstanceOf(globalModelsVue) 99 | expect(model.GlobalModel.globalData).toBe(true) 100 | expect(model.GlobalModel.$options.modelId).toBe('global') 101 | }) 102 | 103 | it('should add the model as property on the providing component', () => { 104 | expect(wrapper.vm.SomeModel).toBeInstanceOf(localVue) 105 | }) 106 | 107 | it('should provide models down the tree', () => { 108 | expect((wrapper.find(consumerComponent) as any).vm.SomeModel).toBe( 109 | wrapper.vm.SomeModel, 110 | ) 111 | expect(wrapper.find('#fooContainer').text()).toBe('bar') 112 | }) 113 | 114 | it('should initialize class-based components', () => { 115 | @Component({}) 116 | class ClassBasedComponent extends Vue { 117 | foo = '123' 118 | 119 | changeFoo(newValue: string) { 120 | this.foo = newValue 121 | } 122 | } 123 | 124 | wrapper = mount({ models: { Model: ClassBasedComponent } } as any, { 125 | localVue, 126 | }) 127 | const Model = wrapper.vm.Model 128 | expect(Model.foo).toBe('123') 129 | Model.changeFoo('456') 130 | expect(Model.foo).toBe('456') 131 | }) 132 | 133 | it('should initialize vue subclasses (Vue.extend)', () => { 134 | // extend twice to make sure multi-level inheritance works as well 135 | const classBasedComponent = Vue.extend({}).extend({ 136 | data() { 137 | return { 138 | foo: '123', 139 | } 140 | }, 141 | methods: { 142 | changeFoo(newValue: string) { 143 | this.foo = newValue 144 | }, 145 | }, 146 | }) 147 | 148 | wrapper = mount({ models: { Model: classBasedComponent } } as any, { 149 | localVue, 150 | }) 151 | const Model = wrapper.vm.Model 152 | expect(Model.foo).toBe('123') 153 | Model.changeFoo('456') 154 | expect(Model.foo).toBe('456') 155 | }) 156 | 157 | it('should allow standard components as part of the chain', () => { 158 | const middleComponent = { 159 | name: 'MiddleComponent', 160 | render(h: any) { 161 | return h(consumerComponent) 162 | }, 163 | } 164 | wrapper = mount(provideComponent(middleComponent), { localVue }) 165 | 166 | expect((wrapper.find(consumerComponent) as any).vm.SomeModel).toBe( 167 | wrapper.vm.SomeModel, 168 | ) 169 | expect(wrapper.find('#fooContainer').text()).toBe('bar') 170 | }) 171 | 172 | it('should be reactive to updates inside the model', async () => { 173 | wrapper.vm.SomeModel.foo = 'otherValue' 174 | await Vue.nextTick() 175 | expect(wrapper.find('#fooContainer').text()).toBe('otherValue') 176 | }) 177 | 178 | it('should resolve circular dependencies between siblings', () => { 179 | wrapper = mount( 180 | { 181 | render(this: any, h: Function) { 182 | return h('div', this.SiblingOne.oneData) 183 | }, 184 | models: { 185 | SiblingOne: { 186 | injectModels: ['SiblingTwo'], 187 | data() { 188 | return { 189 | oneData: 1, 190 | } 191 | }, 192 | }, 193 | SiblingTwo: { 194 | injectModels: ['SiblingOne'], 195 | data() { 196 | return { 197 | twoData: 2, 198 | } 199 | }, 200 | }, 201 | }, 202 | } as any, 203 | { localVue }, 204 | ) 205 | 206 | expect(mockError).not.toHaveBeenCalled() 207 | expect(wrapper.vm.SiblingTwo.SiblingOne.oneData).toBe(1) 208 | expect(wrapper.vm.SiblingOne.SiblingTwo.twoData).toBe(2) 209 | }) 210 | 211 | it('should allow to dynamically create the model with the hosting context', () => { 212 | wrapper = mount( 213 | { 214 | props: ['someKey'], 215 | models(this: any) { 216 | return { 217 | Dynamic: Object.assign({}, SomeModel, { modelId: this.someKey }), 218 | } 219 | }, 220 | render(this: any, h: Function) { 221 | return h('div', this.Dynamic.foo) 222 | }, 223 | } as any, 224 | { 225 | localVue, 226 | propsData: { 227 | someKey: 'uniqueIdentifier123', 228 | }, 229 | }, 230 | ) 231 | 232 | expect(Object.keys(wrapper.vm.$modelRegistry.models)).toEqual([ 233 | 'Dynamic~uniqueIdentifier123', 234 | ]) 235 | expect(wrapper.vm.Dynamic.$options.modelId).toBe('uniqueIdentifier123') 236 | expect(wrapper.text()).toBe('bar') 237 | }) 238 | 239 | it('should allow adding custom mixins', () => { 240 | const localVueWithMixins = createLocalVue() 241 | 242 | localVueWithMixins.use(VueStates, { 243 | mixins: [{ someProp: 'has_an_installed_mixin' }], 244 | }) 245 | 246 | wrapper = mount( 247 | { 248 | models: { 249 | Simple: { 250 | data() { 251 | return { foo: 'bar' } 252 | }, 253 | mixins: [ 254 | { 255 | someOtherProp: 'has_a_local_mixin', 256 | }, 257 | ], 258 | }, 259 | }, 260 | render(this: any, h: Function) { 261 | return h( 262 | 'div', 263 | [ 264 | this.Simple.foo, 265 | this.Simple.$options.someProp, 266 | this.Simple.$options.someOtherProp, 267 | ].join(','), 268 | ) 269 | }, 270 | } as any, 271 | { localVue: localVueWithMixins }, 272 | ) 273 | 274 | expect(wrapper.text()).toBe( 275 | ['bar', 'has_an_installed_mixin', 'has_a_local_mixin'].join(','), 276 | ) 277 | }) 278 | 279 | it('should create a $modelRegistry property on every instance', () => { 280 | expect(wrapper.vm.$modelRegistry).toBeInstanceOf(Registry) 281 | expect((wrapper.find(consumerComponent) as any).vm.$modelRegistry).toBe( 282 | wrapper.vm.$modelRegistry, 283 | ) 284 | }) 285 | 286 | it('should register every created model', () => { 287 | const { models } = wrapper.vm.$modelRegistry 288 | expect(Object.keys(models)).toEqual([ 289 | 'SomeModel~someId', 290 | 'SomeSingleModel~single', 291 | 'SomeStatelessModel~single', 292 | ]) 293 | expect(models['SomeModel~someId']).toBe(wrapper.vm.SomeModel) 294 | expect(models['SomeSingleModel~single']).toBe(wrapper.vm.SomeSingleModel) 295 | }) 296 | 297 | it('should unregister every destroyed model', () => { 298 | wrapper.vm.$destroy() 299 | expect(Object.keys(wrapper.vm.$modelRegistry.models)).toHaveLength(0) 300 | }) 301 | 302 | it('should use imported state if provided', async () => { 303 | // this is executed server-side 304 | wrapper.vm.SomeModel.foo = 'otherValue' 305 | 306 | const exported = wrapper.vm.$modelRegistry.exportState() 307 | expect(Object.keys(exported)).toHaveLength(3) 308 | 309 | const exportedStringified = JSON.stringify(exported) // just to make sure this doesn't make a difference 310 | 311 | // this is executed client-side 312 | const modelRegistry = new Registry(false) 313 | modelRegistry.importState(JSON.parse(exportedStringified)) 314 | 315 | // @ts-ignore 316 | expect(Object.keys(modelRegistry.hydrationData)).toHaveLength(3) 317 | 318 | const hydratedWrapper = mount(provideComponent(consumerComponent), { 319 | localVue, 320 | parentComponent: { modelRegistry } as any, 321 | }) 322 | 323 | expect( 324 | Object.is((hydratedWrapper.vm as any).$modelRegistry, modelRegistry), 325 | ).toBe(true) 326 | 327 | // soft proof, that client and server-side are not accidentally connected 328 | wrapper.vm.SomeModel.foo = 'otherOtherValue' 329 | await Vue.nextTick() 330 | 331 | expect(wrapper.find('#fooContainer').text()).toBe('otherOtherValue') 332 | expect(hydratedWrapper.find('#fooContainer').text()).toBe('otherValue') 333 | 334 | // @ts-ignore 335 | expect(Object.keys(modelRegistry.hydrationData)).toHaveLength(0) 336 | }) 337 | 338 | it('should restore state on replace only if activated', () => { 339 | function testRegistry(restoreOnReplace: boolean) { 340 | const modelRegistry = new Registry(restoreOnReplace) 341 | 342 | function mountModel() { 343 | return (mount(provideComponent(consumerComponent), { 344 | localVue, 345 | parentComponent: { modelRegistry } as any, 346 | }).vm as any).SomeModel 347 | } 348 | 349 | const initialModel = mountModel() 350 | 351 | expect(initialModel.foo).toBe('bar') 352 | initialModel.foo = '123456' 353 | 354 | const resetModel = mountModel() 355 | 356 | expect(resetModel.foo).toBe(restoreOnReplace ? '123456' : 'bar') 357 | } 358 | 359 | testRegistry(true) 360 | testRegistry(false) 361 | }) 362 | }) 363 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------