├── .eslintignore ├── .prettierrc.json ├── .prettierignore ├── .gitignore ├── demo ├── demo-node.js ├── demo-amd.html ├── stack-overflow.html ├── demo-global.html ├── cloneForce.html ├── js │ ├── comm.js │ ├── clone-0.1.1.aio.js │ ├── clone-0.2.0.aio.js │ └── require.js ├── performance2.html ├── performance1.html └── cloneForce-version.html ├── .husky ├── pre-commit └── commit-msg ├── commitlint.config.js ├── .vscode ├── extensions.json └── settings.json ├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE └── workflows │ └── ci.yml ├── .lintstagedrc.cjs ├── TODO.md ├── jslib.json ├── index.d.ts ├── .nycrc ├── .editorconfig ├── config ├── rollup.config.cjs ├── rollup.config.esm.cjs ├── rollup.config.aio.cjs └── rollup.cjs ├── .babelrc ├── CHANGELOG.md ├── .eslintrc.cjs ├── LICENSE ├── test ├── browser │ └── index.html └── test.js ├── doc └── api.md ├── README-zh_CN.md ├── package.json ├── README.md └── src └── index.js /.eslintignore: -------------------------------------------------------------------------------- 1 | dist 2 | require.js 3 | *.ts 4 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true 3 | } 4 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | dist 2 | coverage 3 | package-lock.json 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | coverage 2 | node_modules 3 | dist 4 | .eslintcache 5 | .nyc_output -------------------------------------------------------------------------------- /demo/demo-node.js: -------------------------------------------------------------------------------- 1 | var base = require('../dist/index.js'); 2 | console.log(base.name); 3 | -------------------------------------------------------------------------------- /.husky/pre-commit: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | npx lint-staged 5 | -------------------------------------------------------------------------------- /commitlint.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: ['@commitlint/config-conventional'], 3 | }; 4 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": ["dbaeumer.vscode-eslint", "esbenp.prettier-vscode"] 3 | } 4 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | custom: ['https://yanhaijing.com/mywallet/'] 4 | -------------------------------------------------------------------------------- /.husky/commit-msg: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | . "$(dirname -- "$0")/_/husky.sh" 3 | 4 | npx --no -- commitlint --edit "$1" 5 | -------------------------------------------------------------------------------- /.lintstagedrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | '**/*.{js,mjs,cjs,ts,cts,mts}': ['prettier --write', 'eslint --cache'], 3 | }; 4 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": true, 3 | "editor.defaultFormatter": "esbenp.prettier-vscode" 4 | } 5 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | # 计划列表 2 | 3 | 这里列出会在未来添加的新功能,和已经完成的功能 4 | 5 | - [ ] 支持map类型深拷贝 6 | - [ ] 支持set类型深拷贝 7 | - [ ] 支持weakmap类型深拷贝 8 | - [ ] 支持weakset类型深拷贝 9 | -------------------------------------------------------------------------------- /jslib.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "clone", 3 | "npmname": "@jsmini/clone", 4 | "umdname": "jsmini_clone", 5 | "username": "jsmini", 6 | "type": "js", 7 | "lang": "zh", 8 | "version": "1.3.0" 9 | } 10 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE: -------------------------------------------------------------------------------- 1 | ### 问题是什么 2 | 问题的具体描述,尽量详细 3 | 4 | ### 环境 5 | - 手机: 小米6 6 | - 系统:安卓7.1.1 7 | - 浏览器:chrome 61 8 | - 使用的版本:0.2.0 9 | - 其他版本信息 10 | 11 | ### 在线例子 12 | 如果有请提供在线例子 13 | 14 | ### 其他 15 | 其他信息 16 | -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | export as namespace jsminiClone; 2 | 3 | export function clone(x: T): T; 4 | 5 | export function cloneJSON(x: T, errOrDef?: any): T; 6 | 7 | export function cloneLoop(x: T): T; 8 | 9 | export function cloneForce(x: T): T; 10 | -------------------------------------------------------------------------------- /.nycrc: -------------------------------------------------------------------------------- 1 | { 2 | "check-coverage": true, 3 | "lines": 75, 4 | "statements": 75, 5 | "functions": 0, 6 | "branches": 75, 7 | "reporter": ["lcov", "text"], 8 | "require": ["@babel/register"], 9 | "sourceMap": false, 10 | "instrument": false 11 | } 12 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # 根目录的配置 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | end_of_line = lf 7 | insert_final_newline = true 8 | indent_style = space 9 | indent_size = 4 10 | 11 | [*.html] 12 | indent_size = 2 13 | 14 | [*.{css,less,scss}] 15 | indent_size = 2 16 | 17 | [*.{js,mjs,cjs,ts,cts,mts}] 18 | indent_size = 2 19 | 20 | [*.{json,yml,yaml}] 21 | indent_size = 2 22 | 23 | [*.{sh}] 24 | indent_size = 2 25 | 26 | [*.{md,makrdown}] 27 | indent_size = 2 28 | 29 | [*rc] 30 | indent_size = 2 31 | -------------------------------------------------------------------------------- /config/rollup.config.cjs: -------------------------------------------------------------------------------- 1 | // rollup.config.js 2 | // commonjs 3 | var common = require('./rollup.cjs'); 4 | 5 | module.exports = { 6 | input: 'src/index.js', 7 | output: [ 8 | { 9 | file: 'dist/index.js', 10 | format: 'cjs', 11 | // When export and export default are not used at the same time, set legacy to true. 12 | // legacy: true, 13 | banner: common.banner, 14 | sourcemap: true, 15 | }, 16 | ], 17 | plugins: [common.getCompiler()], 18 | }; 19 | -------------------------------------------------------------------------------- /demo/demo-amd.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document 6 | 7 | 8 | 9 | 10 | 11 | 12 | 17 | 18 | 19 | -------------------------------------------------------------------------------- /config/rollup.config.esm.cjs: -------------------------------------------------------------------------------- 1 | // rollup.config.js 2 | // ES output 3 | var common = require('./rollup.cjs'); 4 | 5 | module.exports = { 6 | input: 'src/index.js', 7 | output: [ 8 | { 9 | file: 'dist/index.esm.js', 10 | format: 'es', 11 | // When export and export default are not used at the same time, set legacy to true. 12 | // legacy: true, 13 | banner: common.banner, 14 | sourcemap: true, 15 | }, 16 | { 17 | file: 'dist/index.mjs', 18 | format: 'es', 19 | // legacy: true, 20 | banner: common.banner, 21 | sourcemap: true, 22 | }, 23 | ], 24 | plugins: [common.getCompiler()], 25 | }; 26 | -------------------------------------------------------------------------------- /.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | [ 4 | "@babel/preset-env", 5 | { 6 | "targets": { 7 | "browsers": "last 2 versions, > 1%, ie >= 11, Android >= 4.1, iOS >= 10.3", 8 | "node": "14" 9 | }, 10 | "modules": "commonjs", 11 | "loose": false 12 | } 13 | ] 14 | ], 15 | "plugins": [ 16 | // [ 17 | // "@babel/plugin-transform-runtime", 18 | // { 19 | // "corejs": 3, 20 | // "versions": "^7.22.15", 21 | // "helpers": true, 22 | // "regenerator": false 23 | // } 24 | // ] 25 | ], 26 | "env": { 27 | "test": { 28 | "plugins": ["istanbul"] 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /demo/stack-overflow.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document 6 | 7 | 8 | 9 | 10 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # 变更日志 2 | 3 | ## 0.6.0 / 2023-11-19 4 | 5 | - 升级 jslib-base 2.3.2 6 | - 支持 sourceMap 7 | - fix: 支持 node >=14.0.0 8 | 9 | ## 0.5.0 / 2023-9-24 10 | 11 | - 升级最新版 jslib-base 12 | - 支持 Node.js ESM 13 | - 升级 @jsmini/type 14 | 15 | ## 0.4.2 / 2019-10-10 16 | 17 | - fix: 修复丢失d.ts的问题 18 | 19 | ## 0.4.0 / 2019-3-2 20 | 21 | - 增加.d.ts文件,支持ts调用 22 | 23 | ## 0.3.1 / 2019-3-2 24 | 25 | - fix: 修复`cloneJSON`ie8下报错 26 | 27 | ## 0.3.0 / 2018-10-18 28 | 29 | - 高级浏览器下,引入weakmap,将`cloneForce`性能提升100% 30 | 31 | ## 0.2.0 / 2018-10-17 32 | 33 | - 将`cloneForce`性能由O(n^2)优化到O(n) 34 | 35 | ## 0.1.1 / 2018-10-14 36 | 37 | - 修复`cloneForce` 提前终止循环的bug 38 | 39 | ## 0.1.0 / 2018-10-10 40 | 41 | - 添加 `clone()` 42 | - 添加 `cloneJSON()` 43 | - 添加 `cloneLoop()` 44 | - 添加 `cloneForce()` 45 | -------------------------------------------------------------------------------- /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@babel/eslint-parser', 3 | env: { 4 | browser: true, 5 | es2021: true, 6 | node: true, 7 | mocha: true, 8 | }, 9 | parserOptions: { 10 | ecmaVersion: 'latest', 11 | sourceType: 'module', 12 | // 即使没有 babelrc 配置文件,也使用 babel-eslint 来解析 13 | requireConfigFile: false, 14 | }, 15 | extends: [ 16 | 'eslint:recommended', 17 | 'plugin:prettier/recommended', 18 | 'plugin:import/recommended', 19 | ], 20 | rules: { 21 | 'no-unused-vars': [ 22 | 2, 23 | { 24 | vars: 'local', 25 | args: 'after-used', 26 | ignoreRestSiblings: true, 27 | varsIgnorePattern: '^_', 28 | argsIgnorePattern: '^_', 29 | }, 30 | ], 31 | eqeqeq: [2], 32 | 'import/no-unresolved': [1], 33 | }, 34 | }; 35 | -------------------------------------------------------------------------------- /config/rollup.config.aio.cjs: -------------------------------------------------------------------------------- 1 | // rollup.config.js 2 | // umd 3 | var nodeResolve = require('@rollup/plugin-node-resolve'); 4 | var commonjs = require('@rollup/plugin-commonjs'); 5 | var terser = require('@rollup/plugin-terser'); 6 | 7 | var common = require('./rollup.cjs'); 8 | 9 | module.exports = { 10 | input: 'src/index.js', 11 | output: [ 12 | { 13 | file: 'dist/index.aio.js', 14 | format: 'umd', 15 | // When export and export default are not used at the same time, set legacy to true. 16 | // legacy: true, 17 | name: common.name, 18 | banner: common.banner, 19 | }, 20 | { 21 | file: 'dist/index.aio.min.js', 22 | format: 'umd', 23 | // legacy: true, 24 | name: common.name, 25 | banner: common.banner, 26 | plugins: [terser()], 27 | }, 28 | ], 29 | plugins: [nodeResolve({}), commonjs({}), common.getCompiler()], 30 | }; 31 | -------------------------------------------------------------------------------- /demo/demo-global.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Document 6 | 7 | 8 | 9 | 10 | 11 | 12 | 31 | 32 | 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (C) 2017-2023 yanhaijing 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /demo/cloneForce.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | cloneForce性能极限 6 | 7 | 8 | 9 | 10 | 35 | 36 | 37 | -------------------------------------------------------------------------------- /demo/js/comm.js: -------------------------------------------------------------------------------- 1 | var clone = jsmini_clone.clone; 2 | var cloneJSON = jsmini_clone.cloneJSON; 3 | var cloneLoop = jsmini_clone.cloneLoop; 4 | var cloneForce = jsmini_clone.cloneForce; 5 | 6 | function createData(deep, breadth) { 7 | var data = {}; 8 | var temp = data; 9 | 10 | for (var i = 0; i < deep; i++) { 11 | temp = temp['data'] = {}; 12 | for (var j = 0; j < breadth; j++) { 13 | temp[j] = j; 14 | } 15 | } 16 | 17 | return data; 18 | } 19 | 20 | function runCount(fn, count) { 21 | var time = Date.now(); 22 | while (count--) { 23 | fn(); 24 | } 25 | 26 | return Date.now() - time; 27 | } 28 | 29 | function runTime(fn, time) { 30 | var stime = Date.now(); 31 | var count = 0; 32 | while (Date.now() - stime < time) { 33 | fn(); 34 | count++; 35 | } 36 | 37 | return count; 38 | } 39 | 40 | function safeRun(name, fn) { 41 | console.log(name, ' start'); 42 | 43 | var time = Date.now(); 44 | 45 | try { 46 | fn(); 47 | } catch (e) { 48 | console.log(e.message); 49 | } 50 | 51 | time = Date.now() - time; 52 | 53 | console.log(name, ' end,耗时: ', time); 54 | return time; 55 | } 56 | -------------------------------------------------------------------------------- /test/browser/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Mocha 5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 20 | 21 | 30 | 31 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /demo/performance2.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 指定时间运行的次数 6 | 7 | 8 | 9 | 10 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /demo/performance1.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 运行指定次数需要的时间 6 | 7 | 8 | 9 | 10 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /config/rollup.cjs: -------------------------------------------------------------------------------- 1 | var babel = require('@rollup/plugin-babel'); 2 | 3 | var pkg = require('../package.json'); 4 | 5 | var version = pkg.version; 6 | 7 | var banner = `/*! 8 | * ${pkg.name} ${version} (https://github.com/jsmini/clone) 9 | * API https://github.com/jsmini/clone/blob/master/doc/api.md 10 | * Copyright 2017-${new Date().getFullYear()} jsmini. All Rights Reserved 11 | * Licensed under MIT (https://github.com/jsmini/clone/blob/master/LICENSE) 12 | */ 13 | `; 14 | 15 | function getCompiler() { 16 | return babel({ 17 | babelrc: false, 18 | presets: [ 19 | [ 20 | '@babel/preset-env', 21 | { 22 | targets: { 23 | browsers: 24 | 'last 2 versions, > 1%, ie >= 11, Android >= 4.1, iOS >= 10.3', 25 | node: '14', 26 | }, 27 | modules: false, 28 | loose: false, 29 | }, 30 | ], 31 | ], 32 | plugins: [ 33 | // [ 34 | // '@babel/plugin-transform-runtime', 35 | // { 36 | // corejs: 3, 37 | // versions: '^7.22.15', 38 | // helpers: true, 39 | // regenerator: false, 40 | // }, 41 | // ], 42 | ], 43 | babelHelpers: 'bundled', 44 | exclude: 'node_modules/**', 45 | }); 46 | } 47 | 48 | exports.name = 'jsmini_clone'; 49 | exports.banner = banner; 50 | exports.getCompiler = getCompiler; 51 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | # This workflow will do a clean installation of node dependencies, cache/restore them, build the source code and run tests across different versions of node 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs 3 | 4 | name: CI 5 | 6 | on: 7 | push: 8 | branches: ['master'] 9 | pull_request: 10 | branches: ['master'] 11 | 12 | jobs: 13 | commitlint: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v3 17 | with: 18 | fetch-depth: 0 19 | - uses: wagoid/commitlint-github-action@v4 20 | 21 | lint: 22 | needs: commitlint 23 | runs-on: ubuntu-latest 24 | steps: 25 | - uses: actions/checkout@v3 26 | - name: Use Node.js 18.x 27 | uses: actions/setup-node@v3 28 | with: 29 | node-version: '18.x' 30 | cache: 'npm' 31 | - run: npm ci 32 | - run: npm run lint 33 | 34 | test: 35 | needs: lint 36 | runs-on: ubuntu-latest 37 | strategy: 38 | matrix: 39 | node-version: [14.x, 16.x, 18.x, 20.x] 40 | # See supported Node.js release schedule at https://nodejs.org/en/about/releases/ 41 | steps: 42 | - uses: actions/checkout@v3 43 | - name: Use Node.js ${{ matrix.node-version }} 44 | uses: actions/setup-node@v3 45 | with: 46 | node-version: ${{ matrix.node-version }} 47 | cache: 'npm' 48 | - run: npm i 49 | - run: npm test 50 | # - run: npm run coveralls --if-present 51 | - run: npm run build --if-present 52 | -------------------------------------------------------------------------------- /demo/cloneForce-version.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | cloneForce不同版本性能对比 6 | 7 | 8 | 9 | 12 | 13 | 16 | 17 | 18 | 19 | 98 | 99 | 100 | -------------------------------------------------------------------------------- /doc/api.md: -------------------------------------------------------------------------------- 1 | # 文档 2 | 3 | clone主要用来进行深拷贝,为什么深拷贝那么简单,还要搞个库?因为深拷贝确实不简单 4 | 5 | ## clone 6 | 7 | 通过递归方式实现的深拷贝 8 | 9 | 支持对象和数组的深拷贝,其他类型数据会浅拷贝;支持父子元素循环引用 10 | 11 | 函数参数和返回值 12 | 13 | - param {\*} x 要进行深拷贝的数据 14 | - return {\*} 如果x为对象或数组,则为x的副本,否则会直接返回 15 | 16 | 举个例子(要包含代码用例) 17 | 18 | ```js 19 | clone(1); // 1 20 | 21 | clone([]); // [] 22 | clone([1, 2, 3]); // 深拷贝的 [1, 2, 3] 23 | clone([1, [2, [3]]]); // 深拷贝的 [1, [2, [3]]] 24 | 25 | clone({}); // {} 26 | clone({ a: 1, b: 1 }); // 深拷贝的 {a: 1, b: 1} 27 | clone({ a1: 1, a2: { b1: 1, b2: 2 } }); // 深拷贝的 {a1: 1, a2: {b1: 1, b2: 2}} 28 | 29 | var a = { a1: 1 }; 30 | a.a2 = a; 31 | clone(a); // 深拷贝的 {a1: 1, a2: a} 支持父子循环引用 32 | ``` 33 | 34 | ## cloneJSON 35 | 36 | 通过`JSON.parse(JSON.stringify(x))`方式实现的深拷贝 37 | 38 | 支持基本类型,对象和数组的深拷贝;不支持循环引用;支持默认值 39 | 40 | 函数参数和返回值 41 | 42 | - param {\*} x 要进行深拷贝的数据 43 | - param {\*} [errOrDef=true] true代表报错是终止程序,其他值则代表报错时提供默认值 44 | - return {\*} 如果x为对象或数组,则为x的副本,否则会直接返回 45 | 46 | 举个例子(要包含代码用例) 47 | 48 | ```js 49 | cloneJSON(1); // 1 50 | 51 | cloneJSON([]); // [] 52 | cloneJSON([1, 2, 3]); // 深拷贝的 [1, 2, 3] 53 | cloneJSON([1, [2, [3]]]); // 深拷贝的 [1, [2, [3]]] 54 | 55 | cloneJSON({}); // {} 56 | cloneJSON({ a: 1, b: 1 }); // 深拷贝的 {a: 1, b: 1} 57 | cloneJSON({ a1: 1, a2: { b1: 1, b2: 2 } }); // 深拷贝的 {a1: 1, a2: {b1: 1, b2: 2}} 58 | 59 | var a = { a1: 1 }; 60 | a.a2 = a; 61 | cloneJSON(a); // 循环引用会报错 62 | cloneJSON(a, {}); // {} 提供默认值,则会返回默认值,不在报错 63 | ``` 64 | 65 | ## cloneLoop 66 | 67 | 通过循环方式实现的深拷贝,如果数据量很大或层级很深,递归的方式会栈溢出,循环的方式则不会 68 | 69 | 支持对象和数组的深拷贝,其他类型数据会浅拷贝;支持父子元素循环引用 70 | 71 | 函数参数和返回值 72 | 73 | - param {\*} x 要进行深拷贝的数据 74 | - return {\*} 如果x为对象或数组,则为x的副本,否则会直接返回 75 | 76 | 举个例子(要包含代码用例) 77 | 78 | ```js 79 | cloneLoop(1); // 1 80 | 81 | cloneLoop([]); // [] 82 | cloneLoop([1, 2, 3]); // 深拷贝的 [1, 2, 3] 83 | cloneLoop([1, [2, [3]]]); // 深拷贝的 [1, [2, [3]]] 84 | 85 | cloneLoop({}); // {} 86 | cloneLoop({ a: 1, b: 1 }); // 深拷贝的 {a: 1, b: 1} 87 | cloneLoop({ a1: 1, a2: { b1: 1, b2: 2 } }); // 深拷贝的 {a1: 1, a2: {b1: 1, b2: 2}} 88 | 89 | var a = { a1: 1 }; 90 | a.a2 = a; 91 | cloneLoop(a); // 深拷贝的 {a1: 1, a2: a} 支持父子循环引用 92 | ``` 93 | 94 | ## cloneForce 95 | 96 | 通过循环方式实现的深拷贝,并且能够支持任意循环引用,保留引用关系 97 | 98 | 支持对象和数组的深拷贝,其他类型数据会浅拷贝 99 | 100 | 最大支持2^32-1各对象的深拷贝,因为唯一数组会越界,当数量超过2000个时,会有明显延时(1s) 101 | 102 | 函数参数和返回值 103 | 104 | - param {\*} x 要进行深拷贝的数据 105 | - return {\*} 如果x为对象或数组,则为x的副本,否则会直接返回 106 | 107 | 举个例子(要包含代码用例) 108 | 109 | ```js 110 | cloneForce(1); // 1 111 | 112 | cloneForce([]); // [] 113 | cloneForce([1, 2, 3]); // 深拷贝的 [1, 2, 3] 114 | cloneForce([1, [2, [3]]]); // 深拷贝的 [1, [2, [3]]] 115 | 116 | cloneForce({}); // {} 117 | cloneForce({ a: 1, b: 1 }); // 深拷贝的 {a: 1, b: 1} 118 | cloneForce({ a1: 1, a2: { b1: 1, b2: 2 } }); // 深拷贝的 {a1: 1, a2: {b1: 1, b2: 2}} 119 | 120 | var a = { a1: { b1: { c1: 1 } } }; 121 | a.a1.b1.c2 = a; 122 | cloneForce(a); // 深拷贝的 {a1: {b1: {c1: 1, c2: a}}} 支持任意循环引用 123 | ``` 124 | -------------------------------------------------------------------------------- /README-zh_CN.md: -------------------------------------------------------------------------------- 1 | # [clone](https://github.com/jsmini/clone) 2 | 3 | [![](https://img.shields.io/badge/Powered%20by-jslib%20base-brightgreen.svg)](https://github.com/yanhaijing/jslib-base) 4 | [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/jsmini/clone/blob/master/LICENSE) 5 | [![CI](https://github.com/jsmini/clone/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/jsmini/clone/actions/workflows/ci.yml) 6 | [![npm](https://img.shields.io/badge/npm-0.6.0-orange.svg)](https://www.npmjs.com/package/@jsmini/clone) 7 | [![NPM downloads](http://img.shields.io/npm/dm/@jsmini/clone.svg?style=flat-square)](http://www.npmtrends.com/@jsmini/clone) 8 | [![Percentage of issues still open](http://isitmaintained.com/badge/open/jsmini/clone.svg)](http://isitmaintained.com/project/jsmini/clone 'Percentage of issues still open') 9 | 10 | 最专业的深拷贝库 11 | 12 | [Engilsh](./README.md) | 简体中文 13 | 14 | ## 兼容性 15 | 16 | 单元测试保证支持如下环境: 17 | 18 | | IE | CH | FF | SF | OP | IOS | 安卓 | Node | 19 | | --- | --- | --- | --- | --- | --- | ---- | ----- | 20 | | 6+ | 23+ | 4+ | 6+ | 10+ | 5+ | 2.3+ | 0.10+ | 21 | 22 | ## 目录介绍 23 | 24 | ``` 25 | . 26 | ├── demo 使用demo 27 | ├── dist 编译产出代码 28 | ├── doc 项目文档 29 | ├── src 源代码目录 30 | ├── test 单元测试 31 | ├── CHANGELOG.md 变更日志 32 | └── TODO.md 计划功能 33 | ``` 34 | 35 | ## 如何使用 36 | 37 | 通过npm下载安装代码 38 | 39 | ```bash 40 | $ npm install --save @jsmini/clone 41 | ``` 42 | 43 | 如果你是node环境 44 | 45 | ```js 46 | var name = require('@jsmini/clone').name; 47 | ``` 48 | 49 | 如果你是webpack等环境 50 | 51 | ```js 52 | import { name } from '@jsmini/clone'; 53 | ``` 54 | 55 | 如果你是requirejs环境 56 | 57 | ```js 58 | requirejs( 59 | ['node_modules/@jsmini/clone/dist/index.aio.js'], 60 | function (jsmini_clone) { 61 | var name = jsmini_clone.name; 62 | }, 63 | ); 64 | ``` 65 | 66 | 如果你是浏览器环境 67 | 68 | ```html 69 | 70 | 71 | 74 | ``` 75 | 76 | ## 文档 77 | 78 | - [API](https://github.com/jsmini/clone/blob/master/doc/api.md) 79 | - [深拷贝的终极探索](https://yanhaijing.com/javascript/2018/10/10/clone-deep/) 80 | 81 | ## 贡献指南 ![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg) 82 | 83 | 首次运行需要先安装依赖 84 | 85 | ```bash 86 | $ npm install 87 | ``` 88 | 89 | 一键打包生成生产代码 90 | 91 | ```bash 92 | $ npm run build 93 | ``` 94 | 95 | 运行单元测试,浏览器环境需要手动测试,位于`test/browser` 96 | 97 | ```bash 98 | $ npm test 99 | ``` 100 | 101 | 修改package.json中的版本号,修改README.md中的版本号,修改CHANGELOG.md,然后发布新版 102 | 103 | ```bash 104 | $ npm run release 105 | ``` 106 | 107 | 将新版本发布到npm 108 | 109 | ```bash 110 | $ npm publish --access=public 111 | ``` 112 | 113 | 重命名项目名称,首次初始化项目时需要修改名字,或者后面项目要改名时使用,需要修改`rename.js`中的`fromName`和`toName`,会自动重命名下面文件中的名字 114 | 115 | - README.md 中的信息 116 | - package.json 中的信息 117 | - config/rollup.js 中的信息 118 | - test/browser/index.html 中的仓库名称 119 | 120 | ```bash 121 | $ npm run rename # 重命名命令 122 | ``` 123 | 124 | ## 贡献者列表 125 | 126 | [contributors](https://github.com/jsmini/clone/graphs/contributors) 127 | 128 | ## 更新日志 129 | 130 | [CHANGELOG.md](https://github.com/jsmini/clone/blob/master/CHANGELOG.md) 131 | 132 | ## 计划列表 133 | 134 | [TODO.md](https://github.com/jsmini/clone/blob/master/TODO.md) 135 | 136 | ## 谁在使用 137 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@jsmini/clone", 3 | "version": "0.6.0", 4 | "description": "A professional deep clone library", 5 | "main": "dist/index.js", 6 | "module": "dist/index.esm.js", 7 | "sideEffects": false, 8 | "exports": { 9 | "node": { 10 | "import": "./dist/index.mjs", 11 | "default": "./dist/index.js" 12 | }, 13 | "default": { 14 | "import": "./dist/index.mjs", 15 | "default": "./dist/index.js" 16 | } 17 | }, 18 | "scripts": { 19 | "rename": "node rename.js", 20 | "clean": "rimraf ./dist ./types", 21 | "lint": "eslint -c .eslintrc.cjs 'src/**/*.js'", 22 | "build:self": "rollup -c config/rollup.config.cjs", 23 | "build:esm": "rollup -c config/rollup.config.esm.cjs", 24 | "build:aio": "rollup -c config/rollup.config.aio.cjs", 25 | "build": "npm run clean && npm run build:self && npm run build:esm && npm run build:aio", 26 | "test": "cross-env NODE_ENV=test nyc mocha", 27 | "release": "npm test && npm run build && git commit -am $npm_package_version && git tag $npm_package_version && git push && git push --tags", 28 | "lint:fix": "eslint --fix -c .eslintrc.cjs 'src/**/*.js' --fix", 29 | "coveralls": "nyc report --reporter=text-lcov | coveralls", 30 | "preinstall": "npx only-allow npm", 31 | "start": "http-server -p 3000 -c-1", 32 | "prepare": "husky install", 33 | "ci": "commit", 34 | "cz": "git-cz" 35 | }, 36 | "author": "yanhaijing", 37 | "license": "MIT", 38 | "repository": { 39 | "type": "git", 40 | "url": "git://github.com/jsmini/clone.git" 41 | }, 42 | "bugs": { 43 | "url": "https://github.com/jsmini/clone/issues" 44 | }, 45 | "files": [ 46 | "/dist", 47 | "/types", 48 | "*.d.ts" 49 | ], 50 | "engines": { 51 | "node": ">=14.0.0", 52 | "npm": ">=6.0.0" 53 | }, 54 | "publishConfig": { 55 | "registry": "https://registry.npmjs.org", 56 | "access": "public" 57 | }, 58 | "config": { 59 | "commitizen": { 60 | "path": "@commitlint/cz-commitlint" 61 | } 62 | }, 63 | "dependencies": { 64 | "@jsmini/type": "^0.11.0" 65 | }, 66 | "devDependencies": { 67 | "babel-plugin-transform-runtime": "6.23.0", 68 | "cdkit": "1.1.0", 69 | "es5-shim": "^4.6.7", 70 | "eslint": "^8.54.0", 71 | "expect.js": "^0.3.1", 72 | "mocha": "^10.2.0", 73 | "rimraf": "^5.0.5", 74 | "rollup": "^3.29.4", 75 | "@js-lib/cli": "^2.3.2", 76 | "cross-env": "^7.0.3", 77 | "@babel/plugin-transform-runtime": "^7.23.3", 78 | "@babel/preset-env": "^7.23.3", 79 | "@babel/register": "^7.22.15", 80 | "babel-plugin-istanbul": "^6.1.1", 81 | "coveralls": "^3.1.1", 82 | "nyc": "^15.1.0", 83 | "source-map-support": "0.5.9", 84 | "http-server": "^14.1.1", 85 | "@babel/eslint-parser": "^7.23.3", 86 | "eslint-config-prettier": "^9.0.0", 87 | "eslint-plugin-import": "^2.29.0", 88 | "eslint-plugin-prettier": "^5.0.1", 89 | "husky": "^8.0.0", 90 | "lint-staged": "^14.0.1", 91 | "prettier": "3.1.0", 92 | "commitizen": "^4.2.4", 93 | "@commitlint/cli": "^16.3.0", 94 | "@commitlint/config-conventional": "^16.2.4", 95 | "@commitlint/cz-commitlint": "^16.3.0", 96 | "@commitlint/format": "^12.1.1", 97 | "@commitlint/prompt-cli": "^16.3.0", 98 | "@rollup/plugin-babel": "^6.0.4", 99 | "@rollup/plugin-commonjs": "^25.0.7", 100 | "@rollup/plugin-node-resolve": "^15.2.3", 101 | "@rollup/plugin-terser": "^0.4.4" 102 | } 103 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # [clone](https://github.com/jsmini/clone) 2 | 3 | [![](https://img.shields.io/badge/Powered%20by-jslib%20base-brightgreen.svg)](https://github.com/yanhaijing/jslib-base) 4 | [![license](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/jsmini/clone/blob/master/LICENSE) 5 | [![CI](https://github.com/jsmini/clone/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/jsmini/clone/actions/workflows/ci.yml) 6 | [![npm](https://img.shields.io/badge/npm-0.6.0-orange.svg)](https://www.npmjs.com/package/@jsmini/clone) 7 | [![NPM downloads](http://img.shields.io/npm/dm/@jsmini/clone.svg?style=flat-square)](http://www.npmtrends.com/@jsmini/clone) 8 | [![Percentage of issues still open](http://isitmaintained.com/badge/open/jsmini/clone.svg)](http://isitmaintained.com/project/jsmini/clone 'Percentage of issues still open') 9 | 10 | A professional deep clone library. 11 | 12 | English | [简体中文](./README-zh_CN.md) 13 | 14 | ## Environment Support 15 | 16 | unit test ensure it supports the following environments. 17 | 18 | | IE/Edge | Chrome | Firefox | Safari | Opera | IOS | Android | Node | 19 | | ------- | ------ | ------- | ------ | ----- | --- | ------- | ----- | 20 | | 6+ | 23+ | 4+ | 6+ | 10+ | 5+ | 2.3+ | 0.10+ | 21 | 22 | ## Directory 23 | 24 | ``` 25 | . 26 | ├── demo 27 | ├── dist # production code 28 | ├── doc # document 29 | ├── src # source code 30 | ├── test # unit test 31 | ├── CHANGELOG.md 32 | └── TODO.md 33 | ``` 34 | 35 | ## Usage 36 | 37 | npm installation 38 | 39 | ```bash 40 | $ npm install --save @jsmini/clone 41 | ``` 42 | 43 | Node.js 44 | 45 | ```js 46 | var name = require('@jsmini/clone').name; 47 | ``` 48 | 49 | webpack 50 | 51 | ```js 52 | import { name } from '@jsmini/clone'; 53 | ``` 54 | 55 | Require.js 56 | 57 | ```js 58 | requirejs( 59 | ['node_modules/@jsmini/clone/dist/index.aio.js'], 60 | function (jsmini_clone) { 61 | var name = jsmini_clone.name; 62 | }, 63 | ); 64 | ``` 65 | 66 | Browser 67 | 68 | ```html 69 | 70 | 71 | 74 | ``` 75 | 76 | ## Document 77 | 78 | - [API](https://github.com/jsmini/clone/blob/master/doc/api.md) 79 | - [深拷贝的终极探索](https://yanhaijing.com/javascript/2018/10/10/clone-deep/) 80 | 81 | ## Contributing Guide ![PRs welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg) 82 | 83 | when initialize, install dependencies 84 | 85 | ```bash 86 | $ npm install 87 | ``` 88 | 89 | builds your code for production to `build` folder 90 | 91 | ```bash 92 | $ npm run build 93 | ``` 94 | 95 | run unit test. notice: borwser enviroment need to test manually. test file is in `test/browser` 96 | 97 | ```bash 98 | $ npm test 99 | ``` 100 | 101 | change the version in package.json and README.md, add your description in CHANGELOG.md, and then release it happily. 102 | 103 | ```bash 104 | $ npm run release 105 | ``` 106 | 107 | publish the new package to npm 108 | 109 | ```bash 110 | $ npm publish --access=public 111 | ``` 112 | 113 | rename project. you need to edit project name when initialize project or anytime you want to rename the project . you need to rename `formName` and `toname` in file `rename.js`,which will automatically rename project name in the following files 114 | 115 | - README.md 116 | - package.json 117 | - config/rollup.js 118 | - test/browser/index.html 119 | 120 | ```bash 121 | $ npm run rename # rename command 122 | ``` 123 | 124 | ## Contributors 125 | 126 | [contributors](https://github.com/jsmini/clone/graphs/contributors) 127 | 128 | ## CHANGELOG 129 | 130 | [CHANGELOG.md](https://github.com/jsmini/clone/blob/master/CHANGELOG.md) 131 | 132 | ## TODO 133 | 134 | [TODO.md](https://github.com/jsmini/clone/blob/master/TODO.md) 135 | 136 | ## who is using 137 | -------------------------------------------------------------------------------- /test/test.js: -------------------------------------------------------------------------------- 1 | var expect = require('expect.js'); 2 | 3 | var clone = require('../src/index.js').clone; 4 | var cloneJSON = require('../src/index.js').cloneJSON; 5 | var cloneLoop = require('../src/index.js').cloneLoop; 6 | var cloneForce = require('../src/index.js').cloneForce; 7 | 8 | function stringify(x) { 9 | return JSON.stringify(x); 10 | } 11 | 12 | describe('单元测试', function () { 13 | this.timeout(1000); 14 | 15 | // 简单值 16 | var simpleList = [ 17 | { 18 | a: 1, 19 | }, 20 | { 21 | a: 'abc', 22 | }, 23 | { 24 | a: true, 25 | }, 26 | { 27 | a: null, 28 | }, 29 | ]; 30 | 31 | // 正常cases 32 | var normalList = [ 33 | { 34 | a: [], 35 | }, 36 | { 37 | a: [1, 2, 3], 38 | }, 39 | { 40 | a: [1, [2, [3]]], 41 | }, 42 | { 43 | a: {}, 44 | }, 45 | { 46 | a: { a: 1, b: 2, c: 3 }, 47 | }, 48 | { 49 | a: { a1: 1, a2: { b1: 1, b2: { c1: 1, c2: 2 } } }, 50 | }, 51 | { 52 | a: { a1: 1, a2: [1, { b1: 1, b2: [{ c1: 1, c2: 2 }] }] }, 53 | }, 54 | ]; 55 | 56 | // 父子循环引用 57 | var a = [1, 2, 3]; 58 | a.push(a); 59 | 60 | var b = { a1: 1, a2: 2, a3: 3 }; 61 | b.a4 = b; 62 | var singleRefList = [ 63 | { 64 | a: a, 65 | }, 66 | { 67 | a: b, 68 | }, 69 | { 70 | a: b, 71 | }, 72 | ]; 73 | 74 | // 多层级循环引用 75 | var a = [1, [2]]; 76 | a[1].push(a); 77 | 78 | var b = { a1: 1, a2: { b1: 1 } }; 79 | b.a2.b2 = b; 80 | var complexRefList = [ 81 | { 82 | a: a, 83 | }, 84 | { 85 | a: b, 86 | }, 87 | { 88 | a: b, 89 | }, 90 | ]; 91 | describe('clone', function () { 92 | it('常规', function () { 93 | for (var i = 0; i < simpleList.length; i++) { 94 | // 确保全等 95 | expect(clone(simpleList[i].a)).to.be(simpleList[i].a); 96 | } 97 | 98 | for (var i = 0; i < normalList.length; i++) { 99 | var temp = clone(normalList[i].a); 100 | 101 | // 确保不全等 102 | expect(temp).not.to.be(normalList[i].a); 103 | // 确保内容一样 104 | expect(temp).to.eql(normalList[i].a); 105 | } 106 | }); 107 | 108 | it('简单循环引用', function () { 109 | var temp = clone(singleRefList[0].a); 110 | expect(temp).to.be(temp[3]); 111 | 112 | var temp = clone(singleRefList[1].a); 113 | expect(temp).to.be(temp['a4']); 114 | }); 115 | }); 116 | 117 | describe('cloneJSON', function () { 118 | it('常规', function () { 119 | for (var i = 0; i < simpleList.length; i++) { 120 | // 确保全等 121 | expect(cloneJSON(simpleList[i].a)).to.be(simpleList[i].a); 122 | } 123 | 124 | for (var i = 0; i < normalList.length; i++) { 125 | var temp = cloneJSON(normalList[i].a); 126 | 127 | // 确保不全等 128 | expect(temp).not.to.be(normalList[i].a); 129 | // 确保内容一样 130 | expect(temp).to.eql(normalList[i].a); 131 | } 132 | }); 133 | }); 134 | 135 | describe('cloneLoop', function () { 136 | it('常规', function () { 137 | for (var i = 0; i < simpleList.length; i++) { 138 | // 确保全等 139 | expect(cloneLoop(simpleList[i].a)).to.be(simpleList[i].a); 140 | } 141 | 142 | for (var i = 0; i < normalList.length; i++) { 143 | var temp = cloneLoop(normalList[i].a); 144 | 145 | // 确保不全等 146 | expect(temp).not.to.be(normalList[i].a); 147 | // 确保内容一样 148 | expect(temp).to.eql(normalList[i].a); 149 | } 150 | }); 151 | 152 | it('简单循环引用', function () { 153 | var temp = cloneLoop(singleRefList[0].a); 154 | expect(temp).to.be(temp[3]); 155 | 156 | var temp = cloneLoop(singleRefList[1].a); 157 | expect(temp).to.be(temp['a4']); 158 | }); 159 | }); 160 | 161 | describe('cloneForce', function () { 162 | it('常规', function () { 163 | for (var i = 0; i < simpleList.length; i++) { 164 | // 确保全等 165 | expect(cloneForce(simpleList[i].a)).to.be(simpleList[i].a); 166 | } 167 | 168 | for (var i = 0; i < normalList.length; i++) { 169 | var temp = cloneForce(normalList[i].a); 170 | 171 | // 确保不全等 172 | expect(temp).not.to.be(normalList[i].a); 173 | // 确保内容一样 174 | expect(temp).to.eql(normalList[i].a); 175 | } 176 | }); 177 | 178 | it('简单循环引用', function () { 179 | var temp = cloneForce(singleRefList[0].a); 180 | expect(temp).to.be(temp[3]); 181 | 182 | var temp = cloneForce(singleRefList[1].a); 183 | expect(temp).to.be(temp['a4']); 184 | }); 185 | 186 | it('复杂循环引用', function () { 187 | var temp = cloneForce(complexRefList[0].a); 188 | expect(temp).to.be(temp[1][1]); 189 | 190 | var temp = cloneForce(complexRefList[1].a); 191 | expect(temp).to.be(temp.a2.b2); 192 | }); 193 | }); 194 | }); 195 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | import { type } from '@jsmini/type'; 2 | 3 | // Object.create(null) 的对象,没有hasOwnProperty方法 4 | function hasOwnProp(obj, key) { 5 | return Object.prototype.hasOwnProperty.call(obj, key); 6 | } 7 | 8 | // 仅对对象和数组进行深拷贝,其他类型,直接返回 9 | function isClone(x) { 10 | const t = type(x); 11 | return t === 'object' || t === 'array'; 12 | } 13 | 14 | // 递归 15 | export function clone(x) { 16 | if (!isClone(x)) return x; 17 | 18 | const t = type(x); 19 | 20 | let res; 21 | 22 | if (t === 'array') { 23 | res = []; 24 | for (let i = 0; i < x.length; i++) { 25 | // 避免一层死循环 a.b = a 26 | res[i] = x[i] === x ? res : clone(x[i]); 27 | } 28 | } else if (t === 'object') { 29 | res = {}; 30 | for (let key in x) { 31 | if (hasOwnProp(x, key)) { 32 | // 避免一层死循环 a.b = a 33 | res[key] = x[key] === x ? res : clone(x[key]); 34 | } 35 | } 36 | } 37 | 38 | return res; 39 | } 40 | 41 | // 通过JSON深拷贝 42 | export function cloneJSON(x, errOrDef = true) { 43 | if (!isClone(x)) return x; 44 | 45 | try { 46 | return JSON.parse(JSON.stringify(x)); 47 | } catch (e) { 48 | if (errOrDef === true) { 49 | throw e; 50 | } else { 51 | try { 52 | // ie8无console 53 | console.error('cloneJSON error: ' + e.message); 54 | // eslint-disable-next-line no-empty 55 | } catch (e) {} 56 | return errOrDef; 57 | } 58 | } 59 | } 60 | 61 | // 循环 62 | export function cloneLoop(x) { 63 | const t = type(x); 64 | 65 | let root = x; 66 | 67 | if (t === 'array') { 68 | root = []; 69 | } else if (t === 'object') { 70 | root = {}; 71 | } 72 | 73 | // 循环数组 74 | const loopList = [ 75 | { 76 | parent: root, 77 | key: undefined, 78 | data: x, 79 | }, 80 | ]; 81 | 82 | while (loopList.length) { 83 | // 深度优先 84 | const node = loopList.pop(); 85 | const parent = node.parent; 86 | const key = node.key; 87 | const data = node.data; 88 | const tt = type(data); 89 | 90 | // 初始化赋值目标,key为undefined则拷贝到父元素,否则拷贝到子元素 91 | let res = parent; 92 | if (typeof key !== 'undefined') { 93 | res = parent[key] = tt === 'array' ? [] : {}; 94 | } 95 | 96 | if (tt === 'array') { 97 | for (let i = 0; i < data.length; i++) { 98 | // 避免一层死循环 a.b = a 99 | if (data[i] === data) { 100 | res[i] = res; 101 | } else if (isClone(data[i])) { 102 | // 下一次循环 103 | loopList.push({ 104 | parent: res, 105 | key: i, 106 | data: data[i], 107 | }); 108 | } else { 109 | res[i] = data[i]; 110 | } 111 | } 112 | } else if (tt === 'object') { 113 | for (let k in data) { 114 | if (hasOwnProp(data, k)) { 115 | // 避免一层死循环 a.b = a 116 | if (data[k] === data) { 117 | res[k] = res; 118 | } else if (isClone(data[k])) { 119 | // 下一次循环 120 | loopList.push({ 121 | parent: res, 122 | key: k, 123 | data: data[k], 124 | }); 125 | } else { 126 | res[k] = data[k]; 127 | } 128 | } 129 | } 130 | } 131 | } 132 | 133 | return root; 134 | } 135 | 136 | const UNIQUE_KEY = 'com.yanhaijing.jsmini.clone' + new Date().getTime(); 137 | 138 | // weakmap:处理对象关联引用 139 | function SimpleWeakmap() { 140 | this.cacheArray = []; 141 | } 142 | 143 | SimpleWeakmap.prototype.set = function (key, value) { 144 | this.cacheArray.push(key); 145 | key[UNIQUE_KEY] = value; 146 | }; 147 | SimpleWeakmap.prototype.get = function (key) { 148 | return key[UNIQUE_KEY]; 149 | }; 150 | SimpleWeakmap.prototype.clear = function () { 151 | for (let i = 0; i < this.cacheArray.length; i++) { 152 | let key = this.cacheArray[i]; 153 | delete key[UNIQUE_KEY]; 154 | } 155 | this.cacheArray.length = 0; 156 | }; 157 | 158 | function getWeakMap() { 159 | let result; 160 | // eslint-disable-next-line eqeqeq 161 | if (typeof WeakMap !== 'undefined' && type(WeakMap) == 'function') { 162 | result = new WeakMap(); 163 | // eslint-disable-next-line eqeqeq 164 | if (type(result) == 'weakmap') { 165 | return result; 166 | } 167 | } 168 | result = new SimpleWeakmap(); 169 | 170 | return result; 171 | } 172 | 173 | export function cloneForce(x) { 174 | const uniqueData = getWeakMap(); 175 | 176 | const t = type(x); 177 | 178 | let root = x; 179 | 180 | if (t === 'array') { 181 | root = []; 182 | } else if (t === 'object') { 183 | root = {}; 184 | } 185 | 186 | // 循环数组 187 | const loopList = [ 188 | { 189 | parent: root, 190 | key: undefined, 191 | data: x, 192 | }, 193 | ]; 194 | 195 | while (loopList.length) { 196 | // 深度优先 197 | const node = loopList.pop(); 198 | const parent = node.parent; 199 | const key = node.key; 200 | const source = node.data; 201 | const tt = type(source); 202 | 203 | // 初始化赋值目标,key为undefined则拷贝到父元素,否则拷贝到子元素 204 | let target = parent; 205 | if (typeof key !== 'undefined') { 206 | target = parent[key] = tt === 'array' ? [] : {}; 207 | } 208 | 209 | // 复杂数据需要缓存操作 210 | if (isClone(source)) { 211 | // 命中缓存,直接返回缓存数据 212 | let uniqueTarget = uniqueData.get(source); 213 | if (uniqueTarget) { 214 | parent[key] = uniqueTarget; 215 | continue; // 中断本次循环 216 | } 217 | 218 | // 未命中缓存,保存到缓存 219 | uniqueData.set(source, target); 220 | } 221 | 222 | if (tt === 'array') { 223 | for (let i = 0; i < source.length; i++) { 224 | if (isClone(source[i])) { 225 | // 下一次循环 226 | loopList.push({ 227 | parent: target, 228 | key: i, 229 | data: source[i], 230 | }); 231 | } else { 232 | target[i] = source[i]; 233 | } 234 | } 235 | } else if (tt === 'object') { 236 | for (let k in source) { 237 | if (hasOwnProp(source, k)) { 238 | if (k === UNIQUE_KEY) continue; 239 | if (isClone(source[k])) { 240 | // 下一次循环 241 | loopList.push({ 242 | parent: target, 243 | key: k, 244 | data: source[k], 245 | }); 246 | } else { 247 | target[k] = source[k]; 248 | } 249 | } 250 | } 251 | } 252 | } 253 | 254 | uniqueData.clear && uniqueData.clear(); 255 | 256 | return root; 257 | } 258 | -------------------------------------------------------------------------------- /demo/js/clone-0.1.1.aio.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * clone 0.1.1 (https://github.com/jsmini/clone) 3 | * API https://github.com/jsmini/clone/blob/master/doc/api.md 4 | * Copyright 2017-2018 jsmini. All Rights Reserved 5 | * Licensed under MIT (https://github.com/jsmini/clone/blob/master/LICENSE) 6 | */ 7 | 8 | (function (global, factory) { 9 | typeof exports === 'object' && typeof module !== 'undefined' 10 | ? factory(exports) 11 | : typeof define === 'function' && define.amd 12 | ? define(['exports'], factory) 13 | : factory((global.jsmini_clone = {})); 14 | })(this, function (exports) { 15 | 'use strict'; 16 | 17 | /*! 18 | * type 0.4.1 (https://github.com/jsmini/type) 19 | * API https://github.com/jsmini/type/blob/master/doc/api.md 20 | * Copyright 2017-2018 jsmini. All Rights Reserved 21 | * Licensed under MIT (https://github.com/jsmini/type/blob/master/LICENSE) 22 | */ 23 | 24 | const toString = Object.prototype.toString; 25 | 26 | function type(x) { 27 | if (x === null) { 28 | return 'null'; 29 | } 30 | 31 | const t = typeof x; 32 | 33 | if (t !== 'object') { 34 | return t; 35 | } 36 | 37 | let c; 38 | try { 39 | c = toString.call(x).slice(8, -1).toLowerCase(); 40 | } catch (e) { 41 | return 'object'; 42 | } 43 | 44 | if (c !== 'object') { 45 | return c; 46 | } 47 | 48 | if (x.constructor == Object) { 49 | return c; 50 | } 51 | 52 | try { 53 | // Object.create(null) 54 | if (Object.getPrototypeOf(x) === null || x.__proto__ === null) { 55 | return 'object'; 56 | } 57 | 58 | return 'unknown'; 59 | } catch (e) { 60 | // ie下无Object.getPrototypeOf 61 | return 'unknown'; 62 | } 63 | } 64 | 65 | // Object.create(null) 的对象,没有hasOwnProperty方法 66 | function hasOwnProp(obj, key) { 67 | return Object.prototype.hasOwnProperty.call(obj, key); 68 | } 69 | 70 | // 仅对对象和数组进行深拷贝,其他类型,直接返回 71 | function isClone(x) { 72 | var t = type(x); 73 | return t === 'object' || t === 'array'; 74 | } 75 | 76 | // 递归 77 | function clone(x) { 78 | if (!isClone(x)) return x; 79 | 80 | var t = type(x); 81 | 82 | var res = void 0; 83 | 84 | if (t === 'array') { 85 | res = []; 86 | for (var i = 0; i < x.length; i++) { 87 | // 避免一层死循环 a.b = a 88 | res[i] = x[i] === x ? res : clone(x[i]); 89 | } 90 | } else if (t === 'object') { 91 | res = {}; 92 | for (var key in x) { 93 | if (hasOwnProp(x, key)) { 94 | // 避免一层死循环 a.b = a 95 | res[key] = x[key] === x ? res : clone(x[key]); 96 | } 97 | } 98 | } 99 | 100 | return res; 101 | } 102 | 103 | // 通过JSON深拷贝 104 | function cloneJSON(x) { 105 | var errOrDef = 106 | arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; 107 | 108 | if (!isClone(x)) return x; 109 | 110 | try { 111 | return JSON.parse(JSON.stringify(x)); 112 | } catch (e) { 113 | if (errOrDef === true) { 114 | throw e; 115 | } else { 116 | console.error('cloneJSON error: ' + e.message); 117 | return errOrDef; 118 | } 119 | } 120 | } 121 | 122 | // 循环 123 | function cloneLoop(x) { 124 | var t = type(x); 125 | 126 | var root = x; 127 | 128 | if (t === 'array') { 129 | root = []; 130 | } else if (t === 'object') { 131 | root = {}; 132 | } 133 | 134 | // 循环数组 135 | var loopList = [ 136 | { 137 | parent: root, 138 | key: undefined, 139 | data: x, 140 | }, 141 | ]; 142 | 143 | while (loopList.length) { 144 | // 深度优先 145 | var node = loopList.pop(); 146 | var parent = node.parent; 147 | var key = node.key; 148 | var data = node.data; 149 | var tt = type(data); 150 | 151 | // 初始化赋值目标,key为undefined则拷贝到父元素,否则拷贝到子元素 152 | var res = parent; 153 | if (typeof key !== 'undefined') { 154 | res = parent[key] = tt === 'array' ? [] : {}; 155 | } 156 | 157 | if (tt === 'array') { 158 | for (var i = 0; i < data.length; i++) { 159 | // 避免一层死循环 a.b = a 160 | if (data[i] === data) { 161 | res[i] = res; 162 | } else if (isClone(data[i])) { 163 | // 下一次循环 164 | loopList.push({ 165 | parent: res, 166 | key: i, 167 | data: data[i], 168 | }); 169 | } else { 170 | res[i] = data[i]; 171 | } 172 | } 173 | } else if (tt === 'object') { 174 | for (var k in data) { 175 | if (hasOwnProp(data, k)) { 176 | // 避免一层死循环 a.b = a 177 | if (data[k] === data) { 178 | res[k] = res; 179 | } else if (isClone(data[k])) { 180 | // 下一次循环 181 | loopList.push({ 182 | parent: res, 183 | key: k, 184 | data: data[k], 185 | }); 186 | } else { 187 | res[k] = data[k]; 188 | } 189 | } 190 | } 191 | } 192 | } 193 | 194 | return root; 195 | } 196 | 197 | function find(arr, item) { 198 | for (var i = 0; i < arr.length; i++) { 199 | if (arr[i].source === item) { 200 | return arr[i]; 201 | } 202 | } 203 | 204 | return null; 205 | } 206 | // 保持引用关系 207 | function cloneForce(x) { 208 | var uniqueList = []; // 用来去重 209 | var t = type(x); 210 | 211 | var root = x; 212 | 213 | if (t === 'array') { 214 | root = []; 215 | } else if (t === 'object') { 216 | root = {}; 217 | } 218 | 219 | // 循环数组 220 | var loopList = [ 221 | { 222 | parent: root, 223 | key: undefined, 224 | data: x, 225 | }, 226 | ]; 227 | 228 | while (loopList.length) { 229 | // 深度优先 230 | var node = loopList.pop(); 231 | var parent = node.parent; 232 | var key = node.key; 233 | var data = node.data; 234 | var tt = type(data); 235 | 236 | // 初始化赋值目标,key为undefined则拷贝到父元素,否则拷贝到子元素 237 | var res = parent; 238 | if (typeof key !== 'undefined') { 239 | res = parent[key] = tt === 'array' ? [] : {}; 240 | } 241 | 242 | // 数据已经存在 243 | var uniqueData = find(uniqueList, data); 244 | if (uniqueData) { 245 | parent[key] = uniqueData.target; 246 | continue; // 中断本次循环 247 | } 248 | 249 | // 数据不存在 250 | // 保存源数据,在拷贝数据中对应的引用 251 | uniqueList.push({ 252 | source: data, 253 | target: res, 254 | }); 255 | 256 | if (tt === 'array') { 257 | for (var i = 0; i < data.length; i++) { 258 | if (isClone(data[i])) { 259 | // 下一次循环 260 | loopList.push({ 261 | parent: res, 262 | key: i, 263 | data: data[i], 264 | }); 265 | } else { 266 | res[i] = data[i]; 267 | } 268 | } 269 | } else if (tt === 'object') { 270 | for (var k in data) { 271 | if (hasOwnProp(data, k)) { 272 | if (isClone(data[k])) { 273 | // 下一次循环 274 | loopList.push({ 275 | parent: res, 276 | key: k, 277 | data: data[k], 278 | }); 279 | } else { 280 | res[k] = data[k]; 281 | } 282 | } 283 | } 284 | } 285 | } 286 | 287 | return root; 288 | } 289 | 290 | exports.clone = clone; 291 | exports.cloneJSON = cloneJSON; 292 | exports.cloneLoop = cloneLoop; 293 | exports.cloneForce = cloneForce; 294 | 295 | Object.defineProperty(exports, '__esModule', { value: true }); 296 | }); 297 | -------------------------------------------------------------------------------- /demo/js/clone-0.2.0.aio.js: -------------------------------------------------------------------------------- 1 | /*! 2 | * clone 0.2.0 (https://github.com/jsmini/clone) 3 | * API https://github.com/jsmini/clone/blob/master/doc/api.md 4 | * Copyright 2017-2018 jsmini. All Rights Reserved 5 | * Licensed under MIT (https://github.com/jsmini/clone/blob/master/LICENSE) 6 | */ 7 | 8 | (function (global, factory) { 9 | typeof exports === 'object' && typeof module !== 'undefined' 10 | ? factory(exports) 11 | : typeof define === 'function' && define.amd 12 | ? define(['exports'], factory) 13 | : factory((global.jsmini_clone = {})); 14 | })(this, function (exports) { 15 | 'use strict'; 16 | 17 | /*! 18 | * type 0.4.1 (https://github.com/jsmini/type) 19 | * API https://github.com/jsmini/type/blob/master/doc/api.md 20 | * Copyright 2017-2018 jsmini. All Rights Reserved 21 | * Licensed under MIT (https://github.com/jsmini/type/blob/master/LICENSE) 22 | */ 23 | 24 | const toString = Object.prototype.toString; 25 | 26 | function type(x) { 27 | if (x === null) { 28 | return 'null'; 29 | } 30 | 31 | const t = typeof x; 32 | 33 | if (t !== 'object') { 34 | return t; 35 | } 36 | 37 | let c; 38 | try { 39 | c = toString.call(x).slice(8, -1).toLowerCase(); 40 | } catch (e) { 41 | return 'object'; 42 | } 43 | 44 | if (c !== 'object') { 45 | return c; 46 | } 47 | 48 | if (x.constructor == Object) { 49 | return c; 50 | } 51 | 52 | try { 53 | // Object.create(null) 54 | if (Object.getPrototypeOf(x) === null || x.__proto__ === null) { 55 | return 'object'; 56 | } 57 | 58 | return 'unknown'; 59 | } catch (e) { 60 | // ie下无Object.getPrototypeOf 61 | return 'unknown'; 62 | } 63 | } 64 | 65 | // Object.create(null) 的对象,没有hasOwnProperty方法 66 | function hasOwnProp(obj, key) { 67 | return Object.prototype.hasOwnProperty.call(obj, key); 68 | } 69 | 70 | // 仅对对象和数组进行深拷贝,其他类型,直接返回 71 | function isClone(x) { 72 | var t = type(x); 73 | return t === 'object' || t === 'array'; 74 | } 75 | 76 | // 递归 77 | function clone(x) { 78 | if (!isClone(x)) return x; 79 | 80 | var t = type(x); 81 | 82 | var res = void 0; 83 | 84 | if (t === 'array') { 85 | res = []; 86 | for (var i = 0; i < x.length; i++) { 87 | // 避免一层死循环 a.b = a 88 | res[i] = x[i] === x ? res : clone(x[i]); 89 | } 90 | } else if (t === 'object') { 91 | res = {}; 92 | for (var key in x) { 93 | if (hasOwnProp(x, key)) { 94 | // 避免一层死循环 a.b = a 95 | res[key] = x[key] === x ? res : clone(x[key]); 96 | } 97 | } 98 | } 99 | 100 | return res; 101 | } 102 | 103 | // 通过JSON深拷贝 104 | function cloneJSON(x) { 105 | var errOrDef = 106 | arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; 107 | 108 | if (!isClone(x)) return x; 109 | 110 | try { 111 | return JSON.parse(JSON.stringify(x)); 112 | } catch (e) { 113 | if (errOrDef === true) { 114 | throw e; 115 | } else { 116 | console.error('cloneJSON error: ' + e.message); 117 | return errOrDef; 118 | } 119 | } 120 | } 121 | 122 | // 循环 123 | function cloneLoop(x) { 124 | var t = type(x); 125 | 126 | var root = x; 127 | 128 | if (t === 'array') { 129 | root = []; 130 | } else if (t === 'object') { 131 | root = {}; 132 | } 133 | 134 | // 循环数组 135 | var loopList = [ 136 | { 137 | parent: root, 138 | key: undefined, 139 | data: x, 140 | }, 141 | ]; 142 | 143 | while (loopList.length) { 144 | // 深度优先 145 | var node = loopList.pop(); 146 | var parent = node.parent; 147 | var key = node.key; 148 | var data = node.data; 149 | var tt = type(data); 150 | 151 | // 初始化赋值目标,key为undefined则拷贝到父元素,否则拷贝到子元素 152 | var res = parent; 153 | if (typeof key !== 'undefined') { 154 | res = parent[key] = tt === 'array' ? [] : {}; 155 | } 156 | 157 | if (tt === 'array') { 158 | for (var i = 0; i < data.length; i++) { 159 | // 避免一层死循环 a.b = a 160 | if (data[i] === data) { 161 | res[i] = res; 162 | } else if (isClone(data[i])) { 163 | // 下一次循环 164 | loopList.push({ 165 | parent: res, 166 | key: i, 167 | data: data[i], 168 | }); 169 | } else { 170 | res[i] = data[i]; 171 | } 172 | } 173 | } else if (tt === 'object') { 174 | for (var k in data) { 175 | if (hasOwnProp(data, k)) { 176 | // 避免一层死循环 a.b = a 177 | if (data[k] === data) { 178 | res[k] = res; 179 | } else if (isClone(data[k])) { 180 | // 下一次循环 181 | loopList.push({ 182 | parent: res, 183 | key: k, 184 | data: data[k], 185 | }); 186 | } else { 187 | res[k] = data[k]; 188 | } 189 | } 190 | } 191 | } 192 | } 193 | 194 | return root; 195 | } 196 | 197 | // 保持引用关系 198 | var UNIQUE_KEY = 'com.yanhaijing.' + new Date().getTime(); 199 | 200 | // 创建数据 201 | function createData() { 202 | return []; 203 | } 204 | // 将数据加入暂存区 205 | function setData(data, source, target) { 206 | var index = data.length; 207 | data[index] = { source: source, target: target }; 208 | source[UNIQUE_KEY] = index; 209 | } 210 | // 查找缓存 211 | function findData(data, source) { 212 | var index = source[UNIQUE_KEY]; 213 | 214 | if (typeof index === 'number') { 215 | return data[index].target; 216 | } 217 | 218 | return false; 219 | } 220 | // 清除缓存 221 | function clearData(data) { 222 | for (var i = 0; i < data.length; i++) { 223 | delete data[i].source[UNIQUE_KEY]; 224 | } 225 | data.length = 0; 226 | } 227 | function cloneForce(x) { 228 | var uniqueData = createData(); 229 | var t = type(x); 230 | 231 | var root = x; 232 | 233 | if (t === 'array') { 234 | root = []; 235 | } else if (t === 'object') { 236 | root = {}; 237 | } 238 | 239 | // 循环数组 240 | var loopList = [ 241 | { 242 | parent: root, 243 | key: undefined, 244 | data: x, 245 | }, 246 | ]; 247 | 248 | while (loopList.length) { 249 | // 深度优先 250 | var node = loopList.pop(); 251 | var parent = node.parent; 252 | var key = node.key; 253 | var source = node.data; 254 | var tt = type(source); 255 | 256 | // 初始化赋值目标,key为undefined则拷贝到父元素,否则拷贝到子元素 257 | var target = parent; 258 | if (typeof key !== 'undefined') { 259 | target = parent[key] = tt === 'array' ? [] : {}; 260 | } 261 | 262 | // 复杂数据需要缓存操作 263 | if (isClone(source)) { 264 | // 命中缓存,直接返回缓存数据 265 | var uniqueTarget = findData(uniqueData, source); 266 | if (uniqueTarget) { 267 | parent[key] = uniqueTarget; 268 | continue; // 中断本次循环 269 | } 270 | 271 | // 未命中缓存,保存到缓存 272 | setData(uniqueData, source, target); 273 | } 274 | 275 | if (tt === 'array') { 276 | for (var i = 0; i < source.length; i++) { 277 | if (isClone(source[i])) { 278 | // 下一次循环 279 | loopList.push({ 280 | parent: target, 281 | key: i, 282 | data: source[i], 283 | }); 284 | } else { 285 | target[i] = source[i]; 286 | } 287 | } 288 | } else if (tt === 'object') { 289 | for (var k in source) { 290 | if (hasOwnProp(source, k)) { 291 | if (k == UNIQUE_KEY) continue; 292 | if (isClone(source[k])) { 293 | // 下一次循环 294 | loopList.push({ 295 | parent: target, 296 | key: k, 297 | data: source[k], 298 | }); 299 | } else { 300 | target[k] = source[k]; 301 | } 302 | } 303 | } 304 | } 305 | } 306 | 307 | clearData(uniqueData); 308 | 309 | return root; 310 | } 311 | 312 | exports.clone = clone; 313 | exports.cloneJSON = cloneJSON; 314 | exports.cloneLoop = cloneLoop; 315 | exports.cloneForce = cloneForce; 316 | 317 | Object.defineProperty(exports, '__esModule', { value: true }); 318 | }); 319 | -------------------------------------------------------------------------------- /demo/js/require.js: -------------------------------------------------------------------------------- 1 | /** vim: et:ts=4:sw=4:sts=4 2 | * @license RequireJS 2.3.5 Copyright jQuery Foundation and other contributors. 3 | * Released under MIT license, https://github.com/requirejs/requirejs/blob/master/LICENSE 4 | */ 5 | //Not using strict: uneven strict support in browsers, #392, and causes 6 | //problems with requirejs.exec()/transpiler plugins that may not be strict. 7 | /*jslint regexp: true, nomen: true, sloppy: true */ 8 | /*global window, navigator, document, importScripts, setTimeout, opera */ 9 | 10 | var requirejs, require, define; 11 | (function (global, setTimeout) { 12 | var req, 13 | s, 14 | head, 15 | baseElement, 16 | dataMain, 17 | src, 18 | interactiveScript, 19 | currentlyAddingScript, 20 | mainScript, 21 | subPath, 22 | version = '2.3.5', 23 | commentRegExp = /\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/gm, 24 | cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, 25 | jsSuffixRegExp = /\.js$/, 26 | currDirRegExp = /^\.\//, 27 | op = Object.prototype, 28 | ostring = op.toString, 29 | hasOwn = op.hasOwnProperty, 30 | isBrowser = !!( 31 | typeof window !== 'undefined' && 32 | typeof navigator !== 'undefined' && 33 | window.document 34 | ), 35 | isWebWorker = !isBrowser && typeof importScripts !== 'undefined', 36 | //PS3 indicates loaded and complete, but need to wait for complete 37 | //specifically. Sequence is 'loading', 'loaded', execution, 38 | // then 'complete'. The UA check is unfortunate, but not sure how 39 | //to feature test w/o causing perf issues. 40 | readyRegExp = 41 | isBrowser && navigator.platform === 'PLAYSTATION 3' 42 | ? /^complete$/ 43 | : /^(complete|loaded)$/, 44 | defContextName = '_', 45 | //Oh the tragedy, detecting opera. See the usage of isOpera for reason. 46 | isOpera = 47 | typeof opera !== 'undefined' && opera.toString() === '[object Opera]', 48 | contexts = {}, 49 | cfg = {}, 50 | globalDefQueue = [], 51 | useInteractive = false; 52 | 53 | //Could match something like ')//comment', do not lose the prefix to comment. 54 | function commentReplace(match, singlePrefix) { 55 | return singlePrefix || ''; 56 | } 57 | 58 | function isFunction(it) { 59 | return ostring.call(it) === '[object Function]'; 60 | } 61 | 62 | function isArray(it) { 63 | return ostring.call(it) === '[object Array]'; 64 | } 65 | 66 | /** 67 | * Helper function for iterating over an array. If the func returns 68 | * a true value, it will break out of the loop. 69 | */ 70 | function each(ary, func) { 71 | if (ary) { 72 | var i; 73 | for (i = 0; i < ary.length; i += 1) { 74 | if (ary[i] && func(ary[i], i, ary)) { 75 | break; 76 | } 77 | } 78 | } 79 | } 80 | 81 | /** 82 | * Helper function for iterating over an array backwards. If the func 83 | * returns a true value, it will break out of the loop. 84 | */ 85 | function eachReverse(ary, func) { 86 | if (ary) { 87 | var i; 88 | for (i = ary.length - 1; i > -1; i -= 1) { 89 | if (ary[i] && func(ary[i], i, ary)) { 90 | break; 91 | } 92 | } 93 | } 94 | } 95 | 96 | function hasProp(obj, prop) { 97 | return hasOwn.call(obj, prop); 98 | } 99 | 100 | function getOwn(obj, prop) { 101 | return hasProp(obj, prop) && obj[prop]; 102 | } 103 | 104 | /** 105 | * Cycles over properties in an object and calls a function for each 106 | * property value. If the function returns a truthy value, then the 107 | * iteration is stopped. 108 | */ 109 | function eachProp(obj, func) { 110 | var prop; 111 | for (prop in obj) { 112 | if (hasProp(obj, prop)) { 113 | if (func(obj[prop], prop)) { 114 | break; 115 | } 116 | } 117 | } 118 | } 119 | 120 | /** 121 | * Simple function to mix in properties from source into target, 122 | * but only if target does not already have a property of the same name. 123 | */ 124 | function mixin(target, source, force, deepStringMixin) { 125 | if (source) { 126 | eachProp(source, function (value, prop) { 127 | if (force || !hasProp(target, prop)) { 128 | if ( 129 | deepStringMixin && 130 | typeof value === 'object' && 131 | value && 132 | !isArray(value) && 133 | !isFunction(value) && 134 | !(value instanceof RegExp) 135 | ) { 136 | if (!target[prop]) { 137 | target[prop] = {}; 138 | } 139 | mixin(target[prop], value, force, deepStringMixin); 140 | } else { 141 | target[prop] = value; 142 | } 143 | } 144 | }); 145 | } 146 | return target; 147 | } 148 | 149 | //Similar to Function.prototype.bind, but the 'this' object is specified 150 | //first, since it is easier to read/figure out what 'this' will be. 151 | function bind(obj, fn) { 152 | return function () { 153 | return fn.apply(obj, arguments); 154 | }; 155 | } 156 | 157 | function scripts() { 158 | return document.getElementsByTagName('script'); 159 | } 160 | 161 | function defaultOnError(err) { 162 | throw err; 163 | } 164 | 165 | //Allow getting a global that is expressed in 166 | //dot notation, like 'a.b.c'. 167 | function getGlobal(value) { 168 | if (!value) { 169 | return value; 170 | } 171 | var g = global; 172 | each(value.split('.'), function (part) { 173 | g = g[part]; 174 | }); 175 | return g; 176 | } 177 | 178 | /** 179 | * Constructs an error with a pointer to an URL with more information. 180 | * @param {String} id the error ID that maps to an ID on a web page. 181 | * @param {String} message human readable error. 182 | * @param {Error} [err] the original error, if there is one. 183 | * 184 | * @returns {Error} 185 | */ 186 | function makeError(id, msg, err, requireModules) { 187 | var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); 188 | e.requireType = id; 189 | e.requireModules = requireModules; 190 | if (err) { 191 | e.originalError = err; 192 | } 193 | return e; 194 | } 195 | 196 | if (typeof define !== 'undefined') { 197 | //If a define is already in play via another AMD loader, 198 | //do not overwrite. 199 | return; 200 | } 201 | 202 | if (typeof requirejs !== 'undefined') { 203 | if (isFunction(requirejs)) { 204 | //Do not overwrite an existing requirejs instance. 205 | return; 206 | } 207 | cfg = requirejs; 208 | requirejs = undefined; 209 | } 210 | 211 | //Allow for a require config object 212 | if (typeof require !== 'undefined' && !isFunction(require)) { 213 | //assume it is a config object. 214 | cfg = require; 215 | require = undefined; 216 | } 217 | 218 | function newContext(contextName) { 219 | var inCheckLoaded, 220 | Module, 221 | context, 222 | handlers, 223 | checkLoadedTimeoutId, 224 | config = { 225 | //Defaults. Do not set a default for map 226 | //config to speed up normalize(), which 227 | //will run faster if there is no default. 228 | waitSeconds: 7, 229 | baseUrl: './', 230 | paths: {}, 231 | bundles: {}, 232 | pkgs: {}, 233 | shim: {}, 234 | config: {}, 235 | }, 236 | registry = {}, 237 | //registry of just enabled modules, to speed 238 | //cycle breaking code when lots of modules 239 | //are registered, but not activated. 240 | enabledRegistry = {}, 241 | undefEvents = {}, 242 | defQueue = [], 243 | defined = {}, 244 | urlFetched = {}, 245 | bundlesMap = {}, 246 | requireCounter = 1, 247 | unnormalizedCounter = 1; 248 | 249 | /** 250 | * Trims the . and .. from an array of path segments. 251 | * It will keep a leading path segment if a .. will become 252 | * the first path segment, to help with module name lookups, 253 | * which act like paths, but can be remapped. But the end result, 254 | * all paths that use this function should look normalized. 255 | * NOTE: this method MODIFIES the input array. 256 | * @param {Array} ary the array of path segments. 257 | */ 258 | function trimDots(ary) { 259 | var i, part; 260 | for (i = 0; i < ary.length; i++) { 261 | part = ary[i]; 262 | if (part === '.') { 263 | ary.splice(i, 1); 264 | i -= 1; 265 | } else if (part === '..') { 266 | // If at the start, or previous value is still .., 267 | // keep them so that when converted to a path it may 268 | // still work when converted to a path, even though 269 | // as an ID it is less than ideal. In larger point 270 | // releases, may be better to just kick out an error. 271 | if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') { 272 | continue; 273 | } else if (i > 0) { 274 | ary.splice(i - 1, 2); 275 | i -= 2; 276 | } 277 | } 278 | } 279 | } 280 | 281 | /** 282 | * Given a relative module name, like ./something, normalize it to 283 | * a real name that can be mapped to a path. 284 | * @param {String} name the relative name 285 | * @param {String} baseName a real name that the name arg is relative 286 | * to. 287 | * @param {Boolean} applyMap apply the map config to the value. Should 288 | * only be done if this normalization is for a dependency ID. 289 | * @returns {String} normalized name 290 | */ 291 | function normalize(name, baseName, applyMap) { 292 | var pkgMain, 293 | mapValue, 294 | nameParts, 295 | i, 296 | j, 297 | nameSegment, 298 | lastIndex, 299 | foundMap, 300 | foundI, 301 | foundStarMap, 302 | starI, 303 | normalizedBaseParts, 304 | baseParts = baseName && baseName.split('/'), 305 | map = config.map, 306 | starMap = map && map['*']; 307 | 308 | //Adjust any relative paths. 309 | if (name) { 310 | name = name.split('/'); 311 | lastIndex = name.length - 1; 312 | 313 | // If wanting node ID compatibility, strip .js from end 314 | // of IDs. Have to do this here, and not in nameToUrl 315 | // because node allows either .js or non .js to map 316 | // to same file. 317 | if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { 318 | name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); 319 | } 320 | 321 | // Starts with a '.' so need the baseName 322 | if (name[0].charAt(0) === '.' && baseParts) { 323 | //Convert baseName to array, and lop off the last part, 324 | //so that . matches that 'directory' and not name of the baseName's 325 | //module. For instance, baseName of 'one/two/three', maps to 326 | //'one/two/three.js', but we want the directory, 'one/two' for 327 | //this normalization. 328 | normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); 329 | name = normalizedBaseParts.concat(name); 330 | } 331 | 332 | trimDots(name); 333 | name = name.join('/'); 334 | } 335 | 336 | //Apply map config if available. 337 | if (applyMap && map && (baseParts || starMap)) { 338 | nameParts = name.split('/'); 339 | 340 | outerLoop: for (i = nameParts.length; i > 0; i -= 1) { 341 | nameSegment = nameParts.slice(0, i).join('/'); 342 | 343 | if (baseParts) { 344 | //Find the longest baseName segment match in the config. 345 | //So, do joins on the biggest to smallest lengths of baseParts. 346 | for (j = baseParts.length; j > 0; j -= 1) { 347 | mapValue = getOwn(map, baseParts.slice(0, j).join('/')); 348 | 349 | //baseName segment has config, find if it has one for 350 | //this name. 351 | if (mapValue) { 352 | mapValue = getOwn(mapValue, nameSegment); 353 | if (mapValue) { 354 | //Match, update name to the new value. 355 | foundMap = mapValue; 356 | foundI = i; 357 | break outerLoop; 358 | } 359 | } 360 | } 361 | } 362 | 363 | //Check for a star map match, but just hold on to it, 364 | //if there is a shorter segment match later in a matching 365 | //config, then favor over this star map. 366 | if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { 367 | foundStarMap = getOwn(starMap, nameSegment); 368 | starI = i; 369 | } 370 | } 371 | 372 | if (!foundMap && foundStarMap) { 373 | foundMap = foundStarMap; 374 | foundI = starI; 375 | } 376 | 377 | if (foundMap) { 378 | nameParts.splice(0, foundI, foundMap); 379 | name = nameParts.join('/'); 380 | } 381 | } 382 | 383 | // If the name points to a package's name, use 384 | // the package main instead. 385 | pkgMain = getOwn(config.pkgs, name); 386 | 387 | return pkgMain ? pkgMain : name; 388 | } 389 | 390 | function removeScript(name) { 391 | if (isBrowser) { 392 | each(scripts(), function (scriptNode) { 393 | if ( 394 | scriptNode.getAttribute('data-requiremodule') === name && 395 | scriptNode.getAttribute('data-requirecontext') === 396 | context.contextName 397 | ) { 398 | scriptNode.parentNode.removeChild(scriptNode); 399 | return true; 400 | } 401 | }); 402 | } 403 | } 404 | 405 | function hasPathFallback(id) { 406 | var pathConfig = getOwn(config.paths, id); 407 | if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { 408 | //Pop off the first array value, since it failed, and 409 | //retry 410 | pathConfig.shift(); 411 | context.require.undef(id); 412 | 413 | //Custom require that does not do map translation, since 414 | //ID is "absolute", already mapped/resolved. 415 | context.makeRequire(null, { 416 | skipMap: true, 417 | })([id]); 418 | 419 | return true; 420 | } 421 | } 422 | 423 | //Turns a plugin!resource to [plugin, resource] 424 | //with the plugin being undefined if the name 425 | //did not have a plugin prefix. 426 | function splitPrefix(name) { 427 | var prefix, 428 | index = name ? name.indexOf('!') : -1; 429 | if (index > -1) { 430 | prefix = name.substring(0, index); 431 | name = name.substring(index + 1, name.length); 432 | } 433 | return [prefix, name]; 434 | } 435 | 436 | /** 437 | * Creates a module mapping that includes plugin prefix, module 438 | * name, and path. If parentModuleMap is provided it will 439 | * also normalize the name via require.normalize() 440 | * 441 | * @param {String} name the module name 442 | * @param {String} [parentModuleMap] parent module map 443 | * for the module name, used to resolve relative names. 444 | * @param {Boolean} isNormalized: is the ID already normalized. 445 | * This is true if this call is done for a define() module ID. 446 | * @param {Boolean} applyMap: apply the map config to the ID. 447 | * Should only be true if this map is for a dependency. 448 | * 449 | * @returns {Object} 450 | */ 451 | function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { 452 | var url, 453 | pluginModule, 454 | suffix, 455 | nameParts, 456 | prefix = null, 457 | parentName = parentModuleMap ? parentModuleMap.name : null, 458 | originalName = name, 459 | isDefine = true, 460 | normalizedName = ''; 461 | 462 | //If no name, then it means it is a require call, generate an 463 | //internal name. 464 | if (!name) { 465 | isDefine = false; 466 | name = '_@r' + (requireCounter += 1); 467 | } 468 | 469 | nameParts = splitPrefix(name); 470 | prefix = nameParts[0]; 471 | name = nameParts[1]; 472 | 473 | if (prefix) { 474 | prefix = normalize(prefix, parentName, applyMap); 475 | pluginModule = getOwn(defined, prefix); 476 | } 477 | 478 | //Account for relative paths if there is a base name. 479 | if (name) { 480 | if (prefix) { 481 | if (isNormalized) { 482 | normalizedName = name; 483 | } else if (pluginModule && pluginModule.normalize) { 484 | //Plugin is loaded, use its normalize method. 485 | normalizedName = pluginModule.normalize(name, function (name) { 486 | return normalize(name, parentName, applyMap); 487 | }); 488 | } else { 489 | // If nested plugin references, then do not try to 490 | // normalize, as it will not normalize correctly. This 491 | // places a restriction on resourceIds, and the longer 492 | // term solution is not to normalize until plugins are 493 | // loaded and all normalizations to allow for async 494 | // loading of a loader plugin. But for now, fixes the 495 | // common uses. Details in #1131 496 | normalizedName = 497 | name.indexOf('!') === -1 498 | ? normalize(name, parentName, applyMap) 499 | : name; 500 | } 501 | } else { 502 | //A regular module. 503 | normalizedName = normalize(name, parentName, applyMap); 504 | 505 | //Normalized name may be a plugin ID due to map config 506 | //application in normalize. The map config values must 507 | //already be normalized, so do not need to redo that part. 508 | nameParts = splitPrefix(normalizedName); 509 | prefix = nameParts[0]; 510 | normalizedName = nameParts[1]; 511 | isNormalized = true; 512 | 513 | url = context.nameToUrl(normalizedName); 514 | } 515 | } 516 | 517 | //If the id is a plugin id that cannot be determined if it needs 518 | //normalization, stamp it with a unique ID so two matching relative 519 | //ids that may conflict can be separate. 520 | suffix = 521 | prefix && !pluginModule && !isNormalized 522 | ? '_unnormalized' + (unnormalizedCounter += 1) 523 | : ''; 524 | 525 | return { 526 | prefix: prefix, 527 | name: normalizedName, 528 | parentMap: parentModuleMap, 529 | unnormalized: !!suffix, 530 | url: url, 531 | originalName: originalName, 532 | isDefine: isDefine, 533 | id: (prefix ? prefix + '!' + normalizedName : normalizedName) + suffix, 534 | }; 535 | } 536 | 537 | function getModule(depMap) { 538 | var id = depMap.id, 539 | mod = getOwn(registry, id); 540 | 541 | if (!mod) { 542 | mod = registry[id] = new context.Module(depMap); 543 | } 544 | 545 | return mod; 546 | } 547 | 548 | function on(depMap, name, fn) { 549 | var id = depMap.id, 550 | mod = getOwn(registry, id); 551 | 552 | if (hasProp(defined, id) && (!mod || mod.defineEmitComplete)) { 553 | if (name === 'defined') { 554 | fn(defined[id]); 555 | } 556 | } else { 557 | mod = getModule(depMap); 558 | if (mod.error && name === 'error') { 559 | fn(mod.error); 560 | } else { 561 | mod.on(name, fn); 562 | } 563 | } 564 | } 565 | 566 | function onError(err, errback) { 567 | var ids = err.requireModules, 568 | notified = false; 569 | 570 | if (errback) { 571 | errback(err); 572 | } else { 573 | each(ids, function (id) { 574 | var mod = getOwn(registry, id); 575 | if (mod) { 576 | //Set error on module, so it skips timeout checks. 577 | mod.error = err; 578 | if (mod.events.error) { 579 | notified = true; 580 | mod.emit('error', err); 581 | } 582 | } 583 | }); 584 | 585 | if (!notified) { 586 | req.onError(err); 587 | } 588 | } 589 | } 590 | 591 | /** 592 | * Internal method to transfer globalQueue items to this context's 593 | * defQueue. 594 | */ 595 | function takeGlobalQueue() { 596 | //Push all the globalDefQueue items into the context's defQueue 597 | if (globalDefQueue.length) { 598 | each(globalDefQueue, function (queueItem) { 599 | var id = queueItem[0]; 600 | if (typeof id === 'string') { 601 | context.defQueueMap[id] = true; 602 | } 603 | defQueue.push(queueItem); 604 | }); 605 | globalDefQueue = []; 606 | } 607 | } 608 | 609 | handlers = { 610 | require: function (mod) { 611 | if (mod.require) { 612 | return mod.require; 613 | } else { 614 | return (mod.require = context.makeRequire(mod.map)); 615 | } 616 | }, 617 | exports: function (mod) { 618 | mod.usingExports = true; 619 | if (mod.map.isDefine) { 620 | if (mod.exports) { 621 | return (defined[mod.map.id] = mod.exports); 622 | } else { 623 | return (mod.exports = defined[mod.map.id] = {}); 624 | } 625 | } 626 | }, 627 | module: function (mod) { 628 | if (mod.module) { 629 | return mod.module; 630 | } else { 631 | return (mod.module = { 632 | id: mod.map.id, 633 | uri: mod.map.url, 634 | config: function () { 635 | return getOwn(config.config, mod.map.id) || {}; 636 | }, 637 | exports: mod.exports || (mod.exports = {}), 638 | }); 639 | } 640 | }, 641 | }; 642 | 643 | function cleanRegistry(id) { 644 | //Clean up machinery used for waiting modules. 645 | delete registry[id]; 646 | delete enabledRegistry[id]; 647 | } 648 | 649 | function breakCycle(mod, traced, processed) { 650 | var id = mod.map.id; 651 | 652 | if (mod.error) { 653 | mod.emit('error', mod.error); 654 | } else { 655 | traced[id] = true; 656 | each(mod.depMaps, function (depMap, i) { 657 | var depId = depMap.id, 658 | dep = getOwn(registry, depId); 659 | 660 | //Only force things that have not completed 661 | //being defined, so still in the registry, 662 | //and only if it has not been matched up 663 | //in the module already. 664 | if (dep && !mod.depMatched[i] && !processed[depId]) { 665 | if (getOwn(traced, depId)) { 666 | mod.defineDep(i, defined[depId]); 667 | mod.check(); //pass false? 668 | } else { 669 | breakCycle(dep, traced, processed); 670 | } 671 | } 672 | }); 673 | processed[id] = true; 674 | } 675 | } 676 | 677 | function checkLoaded() { 678 | var err, 679 | usingPathFallback, 680 | waitInterval = config.waitSeconds * 1000, 681 | //It is possible to disable the wait interval by using waitSeconds of 0. 682 | expired = 683 | waitInterval && 684 | context.startTime + waitInterval < new Date().getTime(), 685 | noLoads = [], 686 | reqCalls = [], 687 | stillLoading = false, 688 | needCycleCheck = true; 689 | 690 | //Do not bother if this call was a result of a cycle break. 691 | if (inCheckLoaded) { 692 | return; 693 | } 694 | 695 | inCheckLoaded = true; 696 | 697 | //Figure out the state of all the modules. 698 | eachProp(enabledRegistry, function (mod) { 699 | var map = mod.map, 700 | modId = map.id; 701 | 702 | //Skip things that are not enabled or in error state. 703 | if (!mod.enabled) { 704 | return; 705 | } 706 | 707 | if (!map.isDefine) { 708 | reqCalls.push(mod); 709 | } 710 | 711 | if (!mod.error) { 712 | //If the module should be executed, and it has not 713 | //been inited and time is up, remember it. 714 | if (!mod.inited && expired) { 715 | if (hasPathFallback(modId)) { 716 | usingPathFallback = true; 717 | stillLoading = true; 718 | } else { 719 | noLoads.push(modId); 720 | removeScript(modId); 721 | } 722 | } else if (!mod.inited && mod.fetched && map.isDefine) { 723 | stillLoading = true; 724 | if (!map.prefix) { 725 | //No reason to keep looking for unfinished 726 | //loading. If the only stillLoading is a 727 | //plugin resource though, keep going, 728 | //because it may be that a plugin resource 729 | //is waiting on a non-plugin cycle. 730 | return (needCycleCheck = false); 731 | } 732 | } 733 | } 734 | }); 735 | 736 | if (expired && noLoads.length) { 737 | //If wait time expired, throw error of unloaded modules. 738 | err = makeError( 739 | 'timeout', 740 | 'Load timeout for modules: ' + noLoads, 741 | null, 742 | noLoads, 743 | ); 744 | err.contextName = context.contextName; 745 | return onError(err); 746 | } 747 | 748 | //Not expired, check for a cycle. 749 | if (needCycleCheck) { 750 | each(reqCalls, function (mod) { 751 | breakCycle(mod, {}, {}); 752 | }); 753 | } 754 | 755 | //If still waiting on loads, and the waiting load is something 756 | //other than a plugin resource, or there are still outstanding 757 | //scripts, then just try back later. 758 | if ((!expired || usingPathFallback) && stillLoading) { 759 | //Something is still waiting to load. Wait for it, but only 760 | //if a timeout is not already in effect. 761 | if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { 762 | checkLoadedTimeoutId = setTimeout(function () { 763 | checkLoadedTimeoutId = 0; 764 | checkLoaded(); 765 | }, 50); 766 | } 767 | } 768 | 769 | inCheckLoaded = false; 770 | } 771 | 772 | Module = function (map) { 773 | this.events = getOwn(undefEvents, map.id) || {}; 774 | this.map = map; 775 | this.shim = getOwn(config.shim, map.id); 776 | this.depExports = []; 777 | this.depMaps = []; 778 | this.depMatched = []; 779 | this.pluginMaps = {}; 780 | this.depCount = 0; 781 | 782 | /* this.exports this.factory 783 | this.depMaps = [], 784 | this.enabled, this.fetched 785 | */ 786 | }; 787 | 788 | Module.prototype = { 789 | init: function (depMaps, factory, errback, options) { 790 | options = options || {}; 791 | 792 | //Do not do more inits if already done. Can happen if there 793 | //are multiple define calls for the same module. That is not 794 | //a normal, common case, but it is also not unexpected. 795 | if (this.inited) { 796 | return; 797 | } 798 | 799 | this.factory = factory; 800 | 801 | if (errback) { 802 | //Register for errors on this module. 803 | this.on('error', errback); 804 | } else if (this.events.error) { 805 | //If no errback already, but there are error listeners 806 | //on this module, set up an errback to pass to the deps. 807 | errback = bind(this, function (err) { 808 | this.emit('error', err); 809 | }); 810 | } 811 | 812 | //Do a copy of the dependency array, so that 813 | //source inputs are not modified. For example 814 | //"shim" deps are passed in here directly, and 815 | //doing a direct modification of the depMaps array 816 | //would affect that config. 817 | this.depMaps = depMaps && depMaps.slice(0); 818 | 819 | this.errback = errback; 820 | 821 | //Indicate this module has be initialized 822 | this.inited = true; 823 | 824 | this.ignore = options.ignore; 825 | 826 | //Could have option to init this module in enabled mode, 827 | //or could have been previously marked as enabled. However, 828 | //the dependencies are not known until init is called. So 829 | //if enabled previously, now trigger dependencies as enabled. 830 | if (options.enabled || this.enabled) { 831 | //Enable this module and dependencies. 832 | //Will call this.check() 833 | this.enable(); 834 | } else { 835 | this.check(); 836 | } 837 | }, 838 | 839 | defineDep: function (i, depExports) { 840 | //Because of cycles, defined callback for a given 841 | //export can be called more than once. 842 | if (!this.depMatched[i]) { 843 | this.depMatched[i] = true; 844 | this.depCount -= 1; 845 | this.depExports[i] = depExports; 846 | } 847 | }, 848 | 849 | fetch: function () { 850 | if (this.fetched) { 851 | return; 852 | } 853 | this.fetched = true; 854 | 855 | context.startTime = new Date().getTime(); 856 | 857 | var map = this.map; 858 | 859 | //If the manager is for a plugin managed resource, 860 | //ask the plugin to load it now. 861 | if (this.shim) { 862 | context.makeRequire(this.map, { 863 | enableBuildCallback: true, 864 | })( 865 | this.shim.deps || [], 866 | bind(this, function () { 867 | return map.prefix ? this.callPlugin() : this.load(); 868 | }), 869 | ); 870 | } else { 871 | //Regular dependency. 872 | return map.prefix ? this.callPlugin() : this.load(); 873 | } 874 | }, 875 | 876 | load: function () { 877 | var url = this.map.url; 878 | 879 | //Regular dependency. 880 | if (!urlFetched[url]) { 881 | urlFetched[url] = true; 882 | context.load(this.map.id, url); 883 | } 884 | }, 885 | 886 | /** 887 | * Checks if the module is ready to define itself, and if so, 888 | * define it. 889 | */ 890 | check: function () { 891 | if (!this.enabled || this.enabling) { 892 | return; 893 | } 894 | 895 | var err, 896 | cjsModule, 897 | id = this.map.id, 898 | depExports = this.depExports, 899 | exports = this.exports, 900 | factory = this.factory; 901 | 902 | if (!this.inited) { 903 | // Only fetch if not already in the defQueue. 904 | if (!hasProp(context.defQueueMap, id)) { 905 | this.fetch(); 906 | } 907 | } else if (this.error) { 908 | this.emit('error', this.error); 909 | } else if (!this.defining) { 910 | //The factory could trigger another require call 911 | //that would result in checking this module to 912 | //define itself again. If already in the process 913 | //of doing that, skip this work. 914 | this.defining = true; 915 | 916 | if (this.depCount < 1 && !this.defined) { 917 | if (isFunction(factory)) { 918 | //If there is an error listener, favor passing 919 | //to that instead of throwing an error. However, 920 | //only do it for define()'d modules. require 921 | //errbacks should not be called for failures in 922 | //their callbacks (#699). However if a global 923 | //onError is set, use that. 924 | if ( 925 | (this.events.error && this.map.isDefine) || 926 | req.onError !== defaultOnError 927 | ) { 928 | try { 929 | exports = context.execCb(id, factory, depExports, exports); 930 | } catch (e) { 931 | err = e; 932 | } 933 | } else { 934 | exports = context.execCb(id, factory, depExports, exports); 935 | } 936 | 937 | // Favor return value over exports. If node/cjs in play, 938 | // then will not have a return value anyway. Favor 939 | // module.exports assignment over exports object. 940 | if (this.map.isDefine && exports === undefined) { 941 | cjsModule = this.module; 942 | if (cjsModule) { 943 | exports = cjsModule.exports; 944 | } else if (this.usingExports) { 945 | //exports already set the defined value. 946 | exports = this.exports; 947 | } 948 | } 949 | 950 | if (err) { 951 | err.requireMap = this.map; 952 | err.requireModules = this.map.isDefine ? [this.map.id] : null; 953 | err.requireType = this.map.isDefine ? 'define' : 'require'; 954 | return onError((this.error = err)); 955 | } 956 | } else { 957 | //Just a literal value 958 | exports = factory; 959 | } 960 | 961 | this.exports = exports; 962 | 963 | if (this.map.isDefine && !this.ignore) { 964 | defined[id] = exports; 965 | 966 | if (req.onResourceLoad) { 967 | var resLoadMaps = []; 968 | each(this.depMaps, function (depMap) { 969 | resLoadMaps.push(depMap.normalizedMap || depMap); 970 | }); 971 | req.onResourceLoad(context, this.map, resLoadMaps); 972 | } 973 | } 974 | 975 | //Clean up 976 | cleanRegistry(id); 977 | 978 | this.defined = true; 979 | } 980 | 981 | //Finished the define stage. Allow calling check again 982 | //to allow define notifications below in the case of a 983 | //cycle. 984 | this.defining = false; 985 | 986 | if (this.defined && !this.defineEmitted) { 987 | this.defineEmitted = true; 988 | this.emit('defined', this.exports); 989 | this.defineEmitComplete = true; 990 | } 991 | } 992 | }, 993 | 994 | callPlugin: function () { 995 | var map = this.map, 996 | id = map.id, 997 | //Map already normalized the prefix. 998 | pluginMap = makeModuleMap(map.prefix); 999 | 1000 | //Mark this as a dependency for this plugin, so it 1001 | //can be traced for cycles. 1002 | this.depMaps.push(pluginMap); 1003 | 1004 | on( 1005 | pluginMap, 1006 | 'defined', 1007 | bind(this, function (plugin) { 1008 | var load, 1009 | normalizedMap, 1010 | normalizedMod, 1011 | bundleId = getOwn(bundlesMap, this.map.id), 1012 | name = this.map.name, 1013 | parentName = this.map.parentMap ? this.map.parentMap.name : null, 1014 | localRequire = context.makeRequire(map.parentMap, { 1015 | enableBuildCallback: true, 1016 | }); 1017 | 1018 | //If current map is not normalized, wait for that 1019 | //normalized name to load instead of continuing. 1020 | if (this.map.unnormalized) { 1021 | //Normalize the ID if the plugin allows it. 1022 | if (plugin.normalize) { 1023 | name = 1024 | plugin.normalize(name, function (name) { 1025 | return normalize(name, parentName, true); 1026 | }) || ''; 1027 | } 1028 | 1029 | //prefix and name should already be normalized, no need 1030 | //for applying map config again either. 1031 | normalizedMap = makeModuleMap( 1032 | map.prefix + '!' + name, 1033 | this.map.parentMap, 1034 | true, 1035 | ); 1036 | on( 1037 | normalizedMap, 1038 | 'defined', 1039 | bind(this, function (value) { 1040 | this.map.normalizedMap = normalizedMap; 1041 | this.init( 1042 | [], 1043 | function () { 1044 | return value; 1045 | }, 1046 | null, 1047 | { 1048 | enabled: true, 1049 | ignore: true, 1050 | }, 1051 | ); 1052 | }), 1053 | ); 1054 | 1055 | normalizedMod = getOwn(registry, normalizedMap.id); 1056 | if (normalizedMod) { 1057 | //Mark this as a dependency for this plugin, so it 1058 | //can be traced for cycles. 1059 | this.depMaps.push(normalizedMap); 1060 | 1061 | if (this.events.error) { 1062 | normalizedMod.on( 1063 | 'error', 1064 | bind(this, function (err) { 1065 | this.emit('error', err); 1066 | }), 1067 | ); 1068 | } 1069 | normalizedMod.enable(); 1070 | } 1071 | 1072 | return; 1073 | } 1074 | 1075 | //If a paths config, then just load that file instead to 1076 | //resolve the plugin, as it is built into that paths layer. 1077 | if (bundleId) { 1078 | this.map.url = context.nameToUrl(bundleId); 1079 | this.load(); 1080 | return; 1081 | } 1082 | 1083 | load = bind(this, function (value) { 1084 | this.init( 1085 | [], 1086 | function () { 1087 | return value; 1088 | }, 1089 | null, 1090 | { 1091 | enabled: true, 1092 | }, 1093 | ); 1094 | }); 1095 | 1096 | load.error = bind(this, function (err) { 1097 | this.inited = true; 1098 | this.error = err; 1099 | err.requireModules = [id]; 1100 | 1101 | //Remove temp unnormalized modules for this module, 1102 | //since they will never be resolved otherwise now. 1103 | eachProp(registry, function (mod) { 1104 | if (mod.map.id.indexOf(id + '_unnormalized') === 0) { 1105 | cleanRegistry(mod.map.id); 1106 | } 1107 | }); 1108 | 1109 | onError(err); 1110 | }); 1111 | 1112 | //Allow plugins to load other code without having to know the 1113 | //context or how to 'complete' the load. 1114 | load.fromText = bind(this, function (text, textAlt) { 1115 | /*jslint evil: true */ 1116 | var moduleName = map.name, 1117 | moduleMap = makeModuleMap(moduleName), 1118 | hasInteractive = useInteractive; 1119 | 1120 | //As of 2.1.0, support just passing the text, to reinforce 1121 | //fromText only being called once per resource. Still 1122 | //support old style of passing moduleName but discard 1123 | //that moduleName in favor of the internal ref. 1124 | if (textAlt) { 1125 | text = textAlt; 1126 | } 1127 | 1128 | //Turn off interactive script matching for IE for any define 1129 | //calls in the text, then turn it back on at the end. 1130 | if (hasInteractive) { 1131 | useInteractive = false; 1132 | } 1133 | 1134 | //Prime the system by creating a module instance for 1135 | //it. 1136 | getModule(moduleMap); 1137 | 1138 | //Transfer any config to this other module. 1139 | if (hasProp(config.config, id)) { 1140 | config.config[moduleName] = config.config[id]; 1141 | } 1142 | 1143 | try { 1144 | req.exec(text); 1145 | } catch (e) { 1146 | return onError( 1147 | makeError( 1148 | 'fromtexteval', 1149 | 'fromText eval for ' + id + ' failed: ' + e, 1150 | e, 1151 | [id], 1152 | ), 1153 | ); 1154 | } 1155 | 1156 | if (hasInteractive) { 1157 | useInteractive = true; 1158 | } 1159 | 1160 | //Mark this as a dependency for the plugin 1161 | //resource 1162 | this.depMaps.push(moduleMap); 1163 | 1164 | //Support anonymous modules. 1165 | context.completeLoad(moduleName); 1166 | 1167 | //Bind the value of that module to the value for this 1168 | //resource ID. 1169 | localRequire([moduleName], load); 1170 | }); 1171 | 1172 | //Use parentName here since the plugin's name is not reliable, 1173 | //could be some weird string with no path that actually wants to 1174 | //reference the parentName's path. 1175 | plugin.load(map.name, localRequire, load, config); 1176 | }), 1177 | ); 1178 | 1179 | context.enable(pluginMap, this); 1180 | this.pluginMaps[pluginMap.id] = pluginMap; 1181 | }, 1182 | 1183 | enable: function () { 1184 | enabledRegistry[this.map.id] = this; 1185 | this.enabled = true; 1186 | 1187 | //Set flag mentioning that the module is enabling, 1188 | //so that immediate calls to the defined callbacks 1189 | //for dependencies do not trigger inadvertent load 1190 | //with the depCount still being zero. 1191 | this.enabling = true; 1192 | 1193 | //Enable each dependency 1194 | each( 1195 | this.depMaps, 1196 | bind(this, function (depMap, i) { 1197 | var id, mod, handler; 1198 | 1199 | if (typeof depMap === 'string') { 1200 | //Dependency needs to be converted to a depMap 1201 | //and wired up to this module. 1202 | depMap = makeModuleMap( 1203 | depMap, 1204 | this.map.isDefine ? this.map : this.map.parentMap, 1205 | false, 1206 | !this.skipMap, 1207 | ); 1208 | this.depMaps[i] = depMap; 1209 | 1210 | handler = getOwn(handlers, depMap.id); 1211 | 1212 | if (handler) { 1213 | this.depExports[i] = handler(this); 1214 | return; 1215 | } 1216 | 1217 | this.depCount += 1; 1218 | 1219 | on( 1220 | depMap, 1221 | 'defined', 1222 | bind(this, function (depExports) { 1223 | if (this.undefed) { 1224 | return; 1225 | } 1226 | this.defineDep(i, depExports); 1227 | this.check(); 1228 | }), 1229 | ); 1230 | 1231 | if (this.errback) { 1232 | on(depMap, 'error', bind(this, this.errback)); 1233 | } else if (this.events.error) { 1234 | // No direct errback on this module, but something 1235 | // else is listening for errors, so be sure to 1236 | // propagate the error correctly. 1237 | on( 1238 | depMap, 1239 | 'error', 1240 | bind(this, function (err) { 1241 | this.emit('error', err); 1242 | }), 1243 | ); 1244 | } 1245 | } 1246 | 1247 | id = depMap.id; 1248 | mod = registry[id]; 1249 | 1250 | //Skip special modules like 'require', 'exports', 'module' 1251 | //Also, don't call enable if it is already enabled, 1252 | //important in circular dependency cases. 1253 | if (!hasProp(handlers, id) && mod && !mod.enabled) { 1254 | context.enable(depMap, this); 1255 | } 1256 | }), 1257 | ); 1258 | 1259 | //Enable each plugin that is used in 1260 | //a dependency 1261 | eachProp( 1262 | this.pluginMaps, 1263 | bind(this, function (pluginMap) { 1264 | var mod = getOwn(registry, pluginMap.id); 1265 | if (mod && !mod.enabled) { 1266 | context.enable(pluginMap, this); 1267 | } 1268 | }), 1269 | ); 1270 | 1271 | this.enabling = false; 1272 | 1273 | this.check(); 1274 | }, 1275 | 1276 | on: function (name, cb) { 1277 | var cbs = this.events[name]; 1278 | if (!cbs) { 1279 | cbs = this.events[name] = []; 1280 | } 1281 | cbs.push(cb); 1282 | }, 1283 | 1284 | emit: function (name, evt) { 1285 | each(this.events[name], function (cb) { 1286 | cb(evt); 1287 | }); 1288 | if (name === 'error') { 1289 | //Now that the error handler was triggered, remove 1290 | //the listeners, since this broken Module instance 1291 | //can stay around for a while in the registry. 1292 | delete this.events[name]; 1293 | } 1294 | }, 1295 | }; 1296 | 1297 | function callGetModule(args) { 1298 | //Skip modules already defined. 1299 | if (!hasProp(defined, args[0])) { 1300 | getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); 1301 | } 1302 | } 1303 | 1304 | function removeListener(node, func, name, ieName) { 1305 | //Favor detachEvent because of IE9 1306 | //issue, see attachEvent/addEventListener comment elsewhere 1307 | //in this file. 1308 | if (node.detachEvent && !isOpera) { 1309 | //Probably IE. If not it will throw an error, which will be 1310 | //useful to know. 1311 | if (ieName) { 1312 | node.detachEvent(ieName, func); 1313 | } 1314 | } else { 1315 | node.removeEventListener(name, func, false); 1316 | } 1317 | } 1318 | 1319 | /** 1320 | * Given an event from a script node, get the requirejs info from it, 1321 | * and then removes the event listeners on the node. 1322 | * @param {Event} evt 1323 | * @returns {Object} 1324 | */ 1325 | function getScriptData(evt) { 1326 | //Using currentTarget instead of target for Firefox 2.0's sake. Not 1327 | //all old browsers will be supported, but this one was easy enough 1328 | //to support and still makes sense. 1329 | var node = evt.currentTarget || evt.srcElement; 1330 | 1331 | //Remove the listeners once here. 1332 | removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); 1333 | removeListener(node, context.onScriptError, 'error'); 1334 | 1335 | return { 1336 | node: node, 1337 | id: node && node.getAttribute('data-requiremodule'), 1338 | }; 1339 | } 1340 | 1341 | function intakeDefines() { 1342 | var args; 1343 | 1344 | //Any defined modules in the global queue, intake them now. 1345 | takeGlobalQueue(); 1346 | 1347 | //Make sure any remaining defQueue items get properly processed. 1348 | while (defQueue.length) { 1349 | args = defQueue.shift(); 1350 | if (args[0] === null) { 1351 | return onError( 1352 | makeError( 1353 | 'mismatch', 1354 | 'Mismatched anonymous define() module: ' + args[args.length - 1], 1355 | ), 1356 | ); 1357 | } else { 1358 | //args are id, deps, factory. Should be normalized by the 1359 | //define() function. 1360 | callGetModule(args); 1361 | } 1362 | } 1363 | context.defQueueMap = {}; 1364 | } 1365 | 1366 | context = { 1367 | config: config, 1368 | contextName: contextName, 1369 | registry: registry, 1370 | defined: defined, 1371 | urlFetched: urlFetched, 1372 | defQueue: defQueue, 1373 | defQueueMap: {}, 1374 | Module: Module, 1375 | makeModuleMap: makeModuleMap, 1376 | nextTick: req.nextTick, 1377 | onError: onError, 1378 | 1379 | /** 1380 | * Set a configuration for the context. 1381 | * @param {Object} cfg config object to integrate. 1382 | */ 1383 | configure: function (cfg) { 1384 | //Make sure the baseUrl ends in a slash. 1385 | if (cfg.baseUrl) { 1386 | if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { 1387 | cfg.baseUrl += '/'; 1388 | } 1389 | } 1390 | 1391 | // Convert old style urlArgs string to a function. 1392 | if (typeof cfg.urlArgs === 'string') { 1393 | var urlArgs = cfg.urlArgs; 1394 | cfg.urlArgs = function (id, url) { 1395 | return (url.indexOf('?') === -1 ? '?' : '&') + urlArgs; 1396 | }; 1397 | } 1398 | 1399 | //Save off the paths since they require special processing, 1400 | //they are additive. 1401 | var shim = config.shim, 1402 | objs = { 1403 | paths: true, 1404 | bundles: true, 1405 | config: true, 1406 | map: true, 1407 | }; 1408 | 1409 | eachProp(cfg, function (value, prop) { 1410 | if (objs[prop]) { 1411 | if (!config[prop]) { 1412 | config[prop] = {}; 1413 | } 1414 | mixin(config[prop], value, true, true); 1415 | } else { 1416 | config[prop] = value; 1417 | } 1418 | }); 1419 | 1420 | //Reverse map the bundles 1421 | if (cfg.bundles) { 1422 | eachProp(cfg.bundles, function (value, prop) { 1423 | each(value, function (v) { 1424 | if (v !== prop) { 1425 | bundlesMap[v] = prop; 1426 | } 1427 | }); 1428 | }); 1429 | } 1430 | 1431 | //Merge shim 1432 | if (cfg.shim) { 1433 | eachProp(cfg.shim, function (value, id) { 1434 | //Normalize the structure 1435 | if (isArray(value)) { 1436 | value = { 1437 | deps: value, 1438 | }; 1439 | } 1440 | if ((value.exports || value.init) && !value.exportsFn) { 1441 | value.exportsFn = context.makeShimExports(value); 1442 | } 1443 | shim[id] = value; 1444 | }); 1445 | config.shim = shim; 1446 | } 1447 | 1448 | //Adjust packages if necessary. 1449 | if (cfg.packages) { 1450 | each(cfg.packages, function (pkgObj) { 1451 | var location, name; 1452 | 1453 | pkgObj = typeof pkgObj === 'string' ? { name: pkgObj } : pkgObj; 1454 | 1455 | name = pkgObj.name; 1456 | location = pkgObj.location; 1457 | if (location) { 1458 | config.paths[name] = pkgObj.location; 1459 | } 1460 | 1461 | //Save pointer to main module ID for pkg name. 1462 | //Remove leading dot in main, so main paths are normalized, 1463 | //and remove any trailing .js, since different package 1464 | //envs have different conventions: some use a module name, 1465 | //some use a file name. 1466 | config.pkgs[name] = 1467 | pkgObj.name + 1468 | '/' + 1469 | (pkgObj.main || 'main') 1470 | .replace(currDirRegExp, '') 1471 | .replace(jsSuffixRegExp, ''); 1472 | }); 1473 | } 1474 | 1475 | //If there are any "waiting to execute" modules in the registry, 1476 | //update the maps for them, since their info, like URLs to load, 1477 | //may have changed. 1478 | eachProp(registry, function (mod, id) { 1479 | //If module already has init called, since it is too 1480 | //late to modify them, and ignore unnormalized ones 1481 | //since they are transient. 1482 | if (!mod.inited && !mod.map.unnormalized) { 1483 | mod.map = makeModuleMap(id, null, true); 1484 | } 1485 | }); 1486 | 1487 | //If a deps array or a config callback is specified, then call 1488 | //require with those args. This is useful when require is defined as a 1489 | //config object before require.js is loaded. 1490 | if (cfg.deps || cfg.callback) { 1491 | context.require(cfg.deps || [], cfg.callback); 1492 | } 1493 | }, 1494 | 1495 | makeShimExports: function (value) { 1496 | function fn() { 1497 | var ret; 1498 | if (value.init) { 1499 | ret = value.init.apply(global, arguments); 1500 | } 1501 | return ret || (value.exports && getGlobal(value.exports)); 1502 | } 1503 | return fn; 1504 | }, 1505 | 1506 | makeRequire: function (relMap, options) { 1507 | options = options || {}; 1508 | 1509 | function localRequire(deps, callback, errback) { 1510 | var id, map, requireMod; 1511 | 1512 | if (options.enableBuildCallback && callback && isFunction(callback)) { 1513 | callback.__requireJsBuild = true; 1514 | } 1515 | 1516 | if (typeof deps === 'string') { 1517 | if (isFunction(callback)) { 1518 | //Invalid call 1519 | return onError( 1520 | makeError('requireargs', 'Invalid require call'), 1521 | errback, 1522 | ); 1523 | } 1524 | 1525 | //If require|exports|module are requested, get the 1526 | //value for them from the special handlers. Caveat: 1527 | //this only works while module is being defined. 1528 | if (relMap && hasProp(handlers, deps)) { 1529 | return handlers[deps](registry[relMap.id]); 1530 | } 1531 | 1532 | //Synchronous access to one module. If require.get is 1533 | //available (as in the Node adapter), prefer that. 1534 | if (req.get) { 1535 | return req.get(context, deps, relMap, localRequire); 1536 | } 1537 | 1538 | //Normalize module name, if it contains . or .. 1539 | map = makeModuleMap(deps, relMap, false, true); 1540 | id = map.id; 1541 | 1542 | if (!hasProp(defined, id)) { 1543 | return onError( 1544 | makeError( 1545 | 'notloaded', 1546 | 'Module name "' + 1547 | id + 1548 | '" has not been loaded yet for context: ' + 1549 | contextName + 1550 | (relMap ? '' : '. Use require([])'), 1551 | ), 1552 | ); 1553 | } 1554 | return defined[id]; 1555 | } 1556 | 1557 | //Grab defines waiting in the global queue. 1558 | intakeDefines(); 1559 | 1560 | //Mark all the dependencies as needing to be loaded. 1561 | context.nextTick(function () { 1562 | //Some defines could have been added since the 1563 | //require call, collect them. 1564 | intakeDefines(); 1565 | 1566 | requireMod = getModule(makeModuleMap(null, relMap)); 1567 | 1568 | //Store if map config should be applied to this require 1569 | //call for dependencies. 1570 | requireMod.skipMap = options.skipMap; 1571 | 1572 | requireMod.init(deps, callback, errback, { 1573 | enabled: true, 1574 | }); 1575 | 1576 | checkLoaded(); 1577 | }); 1578 | 1579 | return localRequire; 1580 | } 1581 | 1582 | mixin(localRequire, { 1583 | isBrowser: isBrowser, 1584 | 1585 | /** 1586 | * Converts a module name + .extension into an URL path. 1587 | * *Requires* the use of a module name. It does not support using 1588 | * plain URLs like nameToUrl. 1589 | */ 1590 | toUrl: function (moduleNamePlusExt) { 1591 | var ext, 1592 | index = moduleNamePlusExt.lastIndexOf('.'), 1593 | segment = moduleNamePlusExt.split('/')[0], 1594 | isRelative = segment === '.' || segment === '..'; 1595 | 1596 | //Have a file extension alias, and it is not the 1597 | //dots from a relative path. 1598 | if (index !== -1 && (!isRelative || index > 1)) { 1599 | ext = moduleNamePlusExt.substring( 1600 | index, 1601 | moduleNamePlusExt.length, 1602 | ); 1603 | moduleNamePlusExt = moduleNamePlusExt.substring(0, index); 1604 | } 1605 | 1606 | return context.nameToUrl( 1607 | normalize(moduleNamePlusExt, relMap && relMap.id, true), 1608 | ext, 1609 | true, 1610 | ); 1611 | }, 1612 | 1613 | defined: function (id) { 1614 | return hasProp(defined, makeModuleMap(id, relMap, false, true).id); 1615 | }, 1616 | 1617 | specified: function (id) { 1618 | id = makeModuleMap(id, relMap, false, true).id; 1619 | return hasProp(defined, id) || hasProp(registry, id); 1620 | }, 1621 | }); 1622 | 1623 | //Only allow undef on top level require calls 1624 | if (!relMap) { 1625 | localRequire.undef = function (id) { 1626 | //Bind any waiting define() calls to this context, 1627 | //fix for #408 1628 | takeGlobalQueue(); 1629 | 1630 | var map = makeModuleMap(id, relMap, true), 1631 | mod = getOwn(registry, id); 1632 | 1633 | mod.undefed = true; 1634 | removeScript(id); 1635 | 1636 | delete defined[id]; 1637 | delete urlFetched[map.url]; 1638 | delete undefEvents[id]; 1639 | 1640 | //Clean queued defines too. Go backwards 1641 | //in array so that the splices do not 1642 | //mess up the iteration. 1643 | eachReverse(defQueue, function (args, i) { 1644 | if (args[0] === id) { 1645 | defQueue.splice(i, 1); 1646 | } 1647 | }); 1648 | delete context.defQueueMap[id]; 1649 | 1650 | if (mod) { 1651 | //Hold on to listeners in case the 1652 | //module will be attempted to be reloaded 1653 | //using a different config. 1654 | if (mod.events.defined) { 1655 | undefEvents[id] = mod.events; 1656 | } 1657 | 1658 | cleanRegistry(id); 1659 | } 1660 | }; 1661 | } 1662 | 1663 | return localRequire; 1664 | }, 1665 | 1666 | /** 1667 | * Called to enable a module if it is still in the registry 1668 | * awaiting enablement. A second arg, parent, the parent module, 1669 | * is passed in for context, when this method is overridden by 1670 | * the optimizer. Not shown here to keep code compact. 1671 | */ 1672 | enable: function (depMap) { 1673 | var mod = getOwn(registry, depMap.id); 1674 | if (mod) { 1675 | getModule(depMap).enable(); 1676 | } 1677 | }, 1678 | 1679 | /** 1680 | * Internal method used by environment adapters to complete a load event. 1681 | * A load event could be a script load or just a load pass from a synchronous 1682 | * load call. 1683 | * @param {String} moduleName the name of the module to potentially complete. 1684 | */ 1685 | completeLoad: function (moduleName) { 1686 | var found, 1687 | args, 1688 | mod, 1689 | shim = getOwn(config.shim, moduleName) || {}, 1690 | shExports = shim.exports; 1691 | 1692 | takeGlobalQueue(); 1693 | 1694 | while (defQueue.length) { 1695 | args = defQueue.shift(); 1696 | if (args[0] === null) { 1697 | args[0] = moduleName; 1698 | //If already found an anonymous module and bound it 1699 | //to this name, then this is some other anon module 1700 | //waiting for its completeLoad to fire. 1701 | if (found) { 1702 | break; 1703 | } 1704 | found = true; 1705 | } else if (args[0] === moduleName) { 1706 | //Found matching define call for this script! 1707 | found = true; 1708 | } 1709 | 1710 | callGetModule(args); 1711 | } 1712 | context.defQueueMap = {}; 1713 | 1714 | //Do this after the cycle of callGetModule in case the result 1715 | //of those calls/init calls changes the registry. 1716 | mod = getOwn(registry, moduleName); 1717 | 1718 | if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { 1719 | if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { 1720 | if (hasPathFallback(moduleName)) { 1721 | return; 1722 | } else { 1723 | return onError( 1724 | makeError( 1725 | 'nodefine', 1726 | 'No define call for ' + moduleName, 1727 | null, 1728 | [moduleName], 1729 | ), 1730 | ); 1731 | } 1732 | } else { 1733 | //A script that does not call define(), so just simulate 1734 | //the call for it. 1735 | callGetModule([moduleName, shim.deps || [], shim.exportsFn]); 1736 | } 1737 | } 1738 | 1739 | checkLoaded(); 1740 | }, 1741 | 1742 | /** 1743 | * Converts a module name to a file path. Supports cases where 1744 | * moduleName may actually be just an URL. 1745 | * Note that it **does not** call normalize on the moduleName, 1746 | * it is assumed to have already been normalized. This is an 1747 | * internal API, not a public one. Use toUrl for the public API. 1748 | */ 1749 | nameToUrl: function (moduleName, ext, skipExt) { 1750 | var paths, 1751 | syms, 1752 | i, 1753 | parentModule, 1754 | url, 1755 | parentPath, 1756 | bundleId, 1757 | pkgMain = getOwn(config.pkgs, moduleName); 1758 | 1759 | if (pkgMain) { 1760 | moduleName = pkgMain; 1761 | } 1762 | 1763 | bundleId = getOwn(bundlesMap, moduleName); 1764 | 1765 | if (bundleId) { 1766 | return context.nameToUrl(bundleId, ext, skipExt); 1767 | } 1768 | 1769 | //If a colon is in the URL, it indicates a protocol is used and it is just 1770 | //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) 1771 | //or ends with .js, then assume the user meant to use an url and not a module id. 1772 | //The slash is important for protocol-less URLs as well as full paths. 1773 | if (req.jsExtRegExp.test(moduleName)) { 1774 | //Just a plain path, not module name lookup, so just return it. 1775 | //Add extension if it is included. This is a bit wonky, only non-.js things pass 1776 | //an extension, this method probably needs to be reworked. 1777 | url = moduleName + (ext || ''); 1778 | } else { 1779 | //A module that needs to be converted to a path. 1780 | paths = config.paths; 1781 | 1782 | syms = moduleName.split('/'); 1783 | //For each module name segment, see if there is a path 1784 | //registered for it. Start with most specific name 1785 | //and work up from it. 1786 | for (i = syms.length; i > 0; i -= 1) { 1787 | parentModule = syms.slice(0, i).join('/'); 1788 | 1789 | parentPath = getOwn(paths, parentModule); 1790 | if (parentPath) { 1791 | //If an array, it means there are a few choices, 1792 | //Choose the one that is desired 1793 | if (isArray(parentPath)) { 1794 | parentPath = parentPath[0]; 1795 | } 1796 | syms.splice(0, i, parentPath); 1797 | break; 1798 | } 1799 | } 1800 | 1801 | //Join the path parts together, then figure out if baseUrl is needed. 1802 | url = syms.join('/'); 1803 | url += 1804 | ext || (/^data\:|^blob\:|\?/.test(url) || skipExt ? '' : '.js'); 1805 | url = 1806 | (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) 1807 | ? '' 1808 | : config.baseUrl) + url; 1809 | } 1810 | 1811 | return config.urlArgs && !/^blob\:/.test(url) 1812 | ? url + config.urlArgs(moduleName, url) 1813 | : url; 1814 | }, 1815 | 1816 | //Delegates to req.load. Broken out as a separate function to 1817 | //allow overriding in the optimizer. 1818 | load: function (id, url) { 1819 | req.load(context, id, url); 1820 | }, 1821 | 1822 | /** 1823 | * Executes a module callback function. Broken out as a separate function 1824 | * solely to allow the build system to sequence the files in the built 1825 | * layer in the right sequence. 1826 | * 1827 | * @private 1828 | */ 1829 | execCb: function (name, callback, args, exports) { 1830 | return callback.apply(exports, args); 1831 | }, 1832 | 1833 | /** 1834 | * callback for script loads, used to check status of loading. 1835 | * 1836 | * @param {Event} evt the event from the browser for the script 1837 | * that was loaded. 1838 | */ 1839 | onScriptLoad: function (evt) { 1840 | //Using currentTarget instead of target for Firefox 2.0's sake. Not 1841 | //all old browsers will be supported, but this one was easy enough 1842 | //to support and still makes sense. 1843 | if ( 1844 | evt.type === 'load' || 1845 | readyRegExp.test((evt.currentTarget || evt.srcElement).readyState) 1846 | ) { 1847 | //Reset interactive script so a script node is not held onto for 1848 | //to long. 1849 | interactiveScript = null; 1850 | 1851 | //Pull out the name of the module and the context. 1852 | var data = getScriptData(evt); 1853 | context.completeLoad(data.id); 1854 | } 1855 | }, 1856 | 1857 | /** 1858 | * Callback for script errors. 1859 | */ 1860 | onScriptError: function (evt) { 1861 | var data = getScriptData(evt); 1862 | if (!hasPathFallback(data.id)) { 1863 | var parents = []; 1864 | eachProp(registry, function (value, key) { 1865 | if (key.indexOf('_@r') !== 0) { 1866 | each(value.depMaps, function (depMap) { 1867 | if (depMap.id === data.id) { 1868 | parents.push(key); 1869 | return true; 1870 | } 1871 | }); 1872 | } 1873 | }); 1874 | return onError( 1875 | makeError( 1876 | 'scripterror', 1877 | 'Script error for "' + 1878 | data.id + 1879 | (parents.length ? '", needed by: ' + parents.join(', ') : '"'), 1880 | evt, 1881 | [data.id], 1882 | ), 1883 | ); 1884 | } 1885 | }, 1886 | }; 1887 | 1888 | context.require = context.makeRequire(); 1889 | return context; 1890 | } 1891 | 1892 | /** 1893 | * Main entry point. 1894 | * 1895 | * If the only argument to require is a string, then the module that 1896 | * is represented by that string is fetched for the appropriate context. 1897 | * 1898 | * If the first argument is an array, then it will be treated as an array 1899 | * of dependency string names to fetch. An optional function callback can 1900 | * be specified to execute when all of those dependencies are available. 1901 | * 1902 | * Make a local req variable to help Caja compliance (it assumes things 1903 | * on a require that are not standardized), and to give a short 1904 | * name for minification/local scope use. 1905 | */ 1906 | req = requirejs = function (deps, callback, errback, optional) { 1907 | //Find the right context, use default 1908 | var context, 1909 | config, 1910 | contextName = defContextName; 1911 | 1912 | // Determine if have config object in the call. 1913 | if (!isArray(deps) && typeof deps !== 'string') { 1914 | // deps is a config object 1915 | config = deps; 1916 | if (isArray(callback)) { 1917 | // Adjust args if there are dependencies 1918 | deps = callback; 1919 | callback = errback; 1920 | errback = optional; 1921 | } else { 1922 | deps = []; 1923 | } 1924 | } 1925 | 1926 | if (config && config.context) { 1927 | contextName = config.context; 1928 | } 1929 | 1930 | context = getOwn(contexts, contextName); 1931 | if (!context) { 1932 | context = contexts[contextName] = req.s.newContext(contextName); 1933 | } 1934 | 1935 | if (config) { 1936 | context.configure(config); 1937 | } 1938 | 1939 | return context.require(deps, callback, errback); 1940 | }; 1941 | 1942 | /** 1943 | * Support require.config() to make it easier to cooperate with other 1944 | * AMD loaders on globally agreed names. 1945 | */ 1946 | req.config = function (config) { 1947 | return req(config); 1948 | }; 1949 | 1950 | /** 1951 | * Execute something after the current tick 1952 | * of the event loop. Override for other envs 1953 | * that have a better solution than setTimeout. 1954 | * @param {Function} fn function to execute later. 1955 | */ 1956 | req.nextTick = 1957 | typeof setTimeout !== 'undefined' 1958 | ? function (fn) { 1959 | setTimeout(fn, 4); 1960 | } 1961 | : function (fn) { 1962 | fn(); 1963 | }; 1964 | 1965 | /** 1966 | * Export require as a global, but only if it does not already exist. 1967 | */ 1968 | if (!require) { 1969 | require = req; 1970 | } 1971 | 1972 | req.version = version; 1973 | 1974 | //Used to filter out dependencies that are already paths. 1975 | req.jsExtRegExp = /^\/|:|\?|\.js$/; 1976 | req.isBrowser = isBrowser; 1977 | s = req.s = { 1978 | contexts: contexts, 1979 | newContext: newContext, 1980 | }; 1981 | 1982 | //Create default context. 1983 | req({}); 1984 | 1985 | //Exports some context-sensitive methods on global require. 1986 | each(['toUrl', 'undef', 'defined', 'specified'], function (prop) { 1987 | //Reference from contexts instead of early binding to default context, 1988 | //so that during builds, the latest instance of the default context 1989 | //with its config gets used. 1990 | req[prop] = function () { 1991 | var ctx = contexts[defContextName]; 1992 | return ctx.require[prop].apply(ctx, arguments); 1993 | }; 1994 | }); 1995 | 1996 | if (isBrowser) { 1997 | head = s.head = document.getElementsByTagName('head')[0]; 1998 | //If BASE tag is in play, using appendChild is a problem for IE6. 1999 | //When that browser dies, this can be removed. Details in this jQuery bug: 2000 | //http://dev.jquery.com/ticket/2709 2001 | baseElement = document.getElementsByTagName('base')[0]; 2002 | if (baseElement) { 2003 | head = s.head = baseElement.parentNode; 2004 | } 2005 | } 2006 | 2007 | /** 2008 | * Any errors that require explicitly generates will be passed to this 2009 | * function. Intercept/override it if you want custom error handling. 2010 | * @param {Error} err the error object. 2011 | */ 2012 | req.onError = defaultOnError; 2013 | 2014 | /** 2015 | * Creates the node for the load command. Only used in browser envs. 2016 | */ 2017 | req.createNode = function (config, moduleName, url) { 2018 | var node = config.xhtml 2019 | ? document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') 2020 | : document.createElement('script'); 2021 | node.type = config.scriptType || 'text/javascript'; 2022 | node.charset = 'utf-8'; 2023 | node.async = true; 2024 | return node; 2025 | }; 2026 | 2027 | /** 2028 | * Does the request to load a module for the browser case. 2029 | * Make this a separate function to allow other environments 2030 | * to override it. 2031 | * 2032 | * @param {Object} context the require context to find state. 2033 | * @param {String} moduleName the name of the module. 2034 | * @param {Object} url the URL to the module. 2035 | */ 2036 | req.load = function (context, moduleName, url) { 2037 | var config = (context && context.config) || {}, 2038 | node; 2039 | if (isBrowser) { 2040 | //In the browser so use a script tag 2041 | node = req.createNode(config, moduleName, url); 2042 | 2043 | node.setAttribute('data-requirecontext', context.contextName); 2044 | node.setAttribute('data-requiremodule', moduleName); 2045 | 2046 | //Set up load listener. Test attachEvent first because IE9 has 2047 | //a subtle issue in its addEventListener and script onload firings 2048 | //that do not match the behavior of all other browsers with 2049 | //addEventListener support, which fire the onload event for a 2050 | //script right after the script execution. See: 2051 | //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution 2052 | //UNFORTUNATELY Opera implements attachEvent but does not follow the script 2053 | //script execution mode. 2054 | if ( 2055 | node.attachEvent && 2056 | //Check if node.attachEvent is artificially added by custom script or 2057 | //natively supported by browser 2058 | //read https://github.com/requirejs/requirejs/issues/187 2059 | //if we can NOT find [native code] then it must NOT natively supported. 2060 | //in IE8, node.attachEvent does not have toString() 2061 | //Note the test for "[native code" with no closing brace, see: 2062 | //https://github.com/requirejs/requirejs/issues/273 2063 | !( 2064 | node.attachEvent.toString && 2065 | node.attachEvent.toString().indexOf('[native code') < 0 2066 | ) && 2067 | !isOpera 2068 | ) { 2069 | //Probably IE. IE (at least 6-8) do not fire 2070 | //script onload right after executing the script, so 2071 | //we cannot tie the anonymous define call to a name. 2072 | //However, IE reports the script as being in 'interactive' 2073 | //readyState at the time of the define call. 2074 | useInteractive = true; 2075 | 2076 | node.attachEvent('onreadystatechange', context.onScriptLoad); 2077 | //It would be great to add an error handler here to catch 2078 | //404s in IE9+. However, onreadystatechange will fire before 2079 | //the error handler, so that does not help. If addEventListener 2080 | //is used, then IE will fire error before load, but we cannot 2081 | //use that pathway given the connect.microsoft.com issue 2082 | //mentioned above about not doing the 'script execute, 2083 | //then fire the script load event listener before execute 2084 | //next script' that other browsers do. 2085 | //Best hope: IE10 fixes the issues, 2086 | //and then destroys all installs of IE 6-9. 2087 | //node.attachEvent('onerror', context.onScriptError); 2088 | } else { 2089 | node.addEventListener('load', context.onScriptLoad, false); 2090 | node.addEventListener('error', context.onScriptError, false); 2091 | } 2092 | node.src = url; 2093 | 2094 | //Calling onNodeCreated after all properties on the node have been 2095 | //set, but before it is placed in the DOM. 2096 | if (config.onNodeCreated) { 2097 | config.onNodeCreated(node, config, moduleName, url); 2098 | } 2099 | 2100 | //For some cache cases in IE 6-8, the script executes before the end 2101 | //of the appendChild execution, so to tie an anonymous define 2102 | //call to the module name (which is stored on the node), hold on 2103 | //to a reference to this node, but clear after the DOM insertion. 2104 | currentlyAddingScript = node; 2105 | if (baseElement) { 2106 | head.insertBefore(node, baseElement); 2107 | } else { 2108 | head.appendChild(node); 2109 | } 2110 | currentlyAddingScript = null; 2111 | 2112 | return node; 2113 | } else if (isWebWorker) { 2114 | try { 2115 | //In a web worker, use importScripts. This is not a very 2116 | //efficient use of importScripts, importScripts will block until 2117 | //its script is downloaded and evaluated. However, if web workers 2118 | //are in play, the expectation is that a build has been done so 2119 | //that only one script needs to be loaded anyway. This may need 2120 | //to be reevaluated if other use cases become common. 2121 | 2122 | // Post a task to the event loop to work around a bug in WebKit 2123 | // where the worker gets garbage-collected after calling 2124 | // importScripts(): https://webkit.org/b/153317 2125 | setTimeout(function () {}, 0); 2126 | importScripts(url); 2127 | 2128 | //Account for anonymous modules 2129 | context.completeLoad(moduleName); 2130 | } catch (e) { 2131 | context.onError( 2132 | makeError( 2133 | 'importscripts', 2134 | 'importScripts failed for ' + moduleName + ' at ' + url, 2135 | e, 2136 | [moduleName], 2137 | ), 2138 | ); 2139 | } 2140 | } 2141 | }; 2142 | 2143 | function getInteractiveScript() { 2144 | if (interactiveScript && interactiveScript.readyState === 'interactive') { 2145 | return interactiveScript; 2146 | } 2147 | 2148 | eachReverse(scripts(), function (script) { 2149 | if (script.readyState === 'interactive') { 2150 | return (interactiveScript = script); 2151 | } 2152 | }); 2153 | return interactiveScript; 2154 | } 2155 | 2156 | //Look for a data-main script attribute, which could also adjust the baseUrl. 2157 | if (isBrowser && !cfg.skipDataMain) { 2158 | //Figure out baseUrl. Get it from the script tag with require.js in it. 2159 | eachReverse(scripts(), function (script) { 2160 | //Set the 'head' where we can append children by 2161 | //using the script's parent. 2162 | if (!head) { 2163 | head = script.parentNode; 2164 | } 2165 | 2166 | //Look for a data-main attribute to set main script for the page 2167 | //to load. If it is there, the path to data main becomes the 2168 | //baseUrl, if it is not already set. 2169 | dataMain = script.getAttribute('data-main'); 2170 | if (dataMain) { 2171 | //Preserve dataMain in case it is a path (i.e. contains '?') 2172 | mainScript = dataMain; 2173 | 2174 | //Set final baseUrl if there is not already an explicit one, 2175 | //but only do so if the data-main value is not a loader plugin 2176 | //module ID. 2177 | if (!cfg.baseUrl && mainScript.indexOf('!') === -1) { 2178 | //Pull off the directory of data-main for use as the 2179 | //baseUrl. 2180 | src = mainScript.split('/'); 2181 | mainScript = src.pop(); 2182 | subPath = src.length ? src.join('/') + '/' : './'; 2183 | 2184 | cfg.baseUrl = subPath; 2185 | } 2186 | 2187 | //Strip off any trailing .js since mainScript is now 2188 | //like a module name. 2189 | mainScript = mainScript.replace(jsSuffixRegExp, ''); 2190 | 2191 | //If mainScript is still a path, fall back to dataMain 2192 | if (req.jsExtRegExp.test(mainScript)) { 2193 | mainScript = dataMain; 2194 | } 2195 | 2196 | //Put the data-main script in the files to load. 2197 | cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]; 2198 | 2199 | return true; 2200 | } 2201 | }); 2202 | } 2203 | 2204 | /** 2205 | * The function that handles definitions of modules. Differs from 2206 | * require() in that a string for the module should be the first argument, 2207 | * and the function to execute after dependencies are loaded should 2208 | * return a value to define the module corresponding to the first argument's 2209 | * name. 2210 | */ 2211 | define = function (name, deps, callback) { 2212 | var node, context; 2213 | 2214 | //Allow for anonymous modules 2215 | if (typeof name !== 'string') { 2216 | //Adjust args appropriately 2217 | callback = deps; 2218 | deps = name; 2219 | name = null; 2220 | } 2221 | 2222 | //This module may not have dependencies 2223 | if (!isArray(deps)) { 2224 | callback = deps; 2225 | deps = null; 2226 | } 2227 | 2228 | //If no name, and callback is a function, then figure out if it a 2229 | //CommonJS thing with dependencies. 2230 | if (!deps && isFunction(callback)) { 2231 | deps = []; 2232 | //Remove comments from the callback string, 2233 | //look for require calls, and pull them into the dependencies, 2234 | //but only if there are function args. 2235 | if (callback.length) { 2236 | callback 2237 | .toString() 2238 | .replace(commentRegExp, commentReplace) 2239 | .replace(cjsRequireRegExp, function (match, dep) { 2240 | deps.push(dep); 2241 | }); 2242 | 2243 | //May be a CommonJS thing even without require calls, but still 2244 | //could use exports, and module. Avoid doing exports and module 2245 | //work though if it just needs require. 2246 | //REQUIRES the function to expect the CommonJS variables in the 2247 | //order listed below. 2248 | deps = ( 2249 | callback.length === 1 ? ['require'] : ['require', 'exports', 'module'] 2250 | ).concat(deps); 2251 | } 2252 | } 2253 | 2254 | //If in IE 6-8 and hit an anonymous define() call, do the interactive 2255 | //work. 2256 | if (useInteractive) { 2257 | node = currentlyAddingScript || getInteractiveScript(); 2258 | if (node) { 2259 | if (!name) { 2260 | name = node.getAttribute('data-requiremodule'); 2261 | } 2262 | context = contexts[node.getAttribute('data-requirecontext')]; 2263 | } 2264 | } 2265 | 2266 | //Always save off evaluating the def call until the script onload handler. 2267 | //This allows multiple modules to be in a file without prematurely 2268 | //tracing dependencies, and allows for anonymous module support, 2269 | //where the module name is not known until the script onload event 2270 | //occurs. If no context, use the global queue, and get it processed 2271 | //in the onscript load callback. 2272 | if (context) { 2273 | context.defQueue.push([name, deps, callback]); 2274 | context.defQueueMap[name] = true; 2275 | } else { 2276 | globalDefQueue.push([name, deps, callback]); 2277 | } 2278 | }; 2279 | 2280 | define.amd = { 2281 | jQuery: true, 2282 | }; 2283 | 2284 | /** 2285 | * Executes the text. Normally just uses eval, but can be modified 2286 | * to use a better, environment-specific call. Only used for transpiling 2287 | * loader plugins, not for plain JS modules. 2288 | * @param {String} text the text to execute/evaluate. 2289 | */ 2290 | req.exec = function (text) { 2291 | /*jslint evil: true */ 2292 | return eval(text); 2293 | }; 2294 | 2295 | //Set up with config info. 2296 | req(cfg); 2297 | })(this, typeof setTimeout === 'undefined' ? undefined : setTimeout); 2298 | --------------------------------------------------------------------------------