{"name":"copy-anything","version":"4.0.4","keywords":["copy","clone","json-stringify","stringify-parse","object","copy-objects","clone-objects","json-stringify-json-parse","deep-clone","deep-copy","typescript","ts"],"author":{"url":"https://cycraft.co","name":"Luca Ban - Mesqueeb"},"license":"MIT","_id":"copy-anything@4.0.4","maintainers":[{"name":"mesqueeb","email":"mesqueeb@gmail.com"}],"homepage":"https://github.com/mesqueeb/copy-anything#readme","bugs":{"url":"https://github.com/mesqueeb/copy-anything/issues"},"dist":{"shasum":"7f4dcbc5aacb27276806fc1c6700d8e3ef3b2e4a","tarball":"http://registry-npm.ywwl.com/copy-anything/download/copy-anything-4.0.4.tgz","fileCount":5,"integrity":"sha512-1n4wXJ1/kVjOVADnP++yEh46uvvdvxDFRHPRlc66ya2jh27OwwNMcj6Fz4lf5Mnu8mc8aAqnfk49LYD2612AOA==","signatures":[{"sig":"MEUCIEc8KUGLvAL9VzODcqTYmawiSXMmhLEv1dvG4USIPuDIAiEA2v8GoSezitP3MbBqvBs4rwA33Dq2Nx4Z8ApLaCUXzb0=","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":9244,"size":3807,"noattachment":false,"key":"/copy-anything/-/copy-anything-4.0.4.tgz"},"type":"module","engines":{"node":">=18"},"exports":{".":"./dist/index.js"},"funding":"https://github.com/sponsors/mesqueeb","gitHead":"fe760210066f0c331322825963beb4c5a735a16c","scripts":{"lint":"tsc --noEmit && eslint ./src","test":"vitest run","build":"del-cli dist && tsc","release":"npm run lint && npm run build && np"},"_npmUser":{"name":"mesqueeb","email":"mesqueeb@gmail.com"},"repository":{"url":"git+https://github.com/mesqueeb/copy-anything.git","type":"git"},"_npmVersion":"10.9.2","description":"An optimised way to copy'ing an object. A small and simple integration","directories":{},"sideEffects":false,"_nodeVersion":"22.14.0","dependencies":{"is-what":"^5.2.0"},"_hasShrinkwrap":false,"devDependencies":{"np":"^10.2.0","vitest":"^3.0.9","del-cli":"^6.0.0","@cycraft/eslint":"^0.4.4","@cycraft/tsconfig":"^0.1.2"},"_npmOperationalInternal":{"tmp":"tmp/copy-anything_4.0.4_1742839055030_0.5830144321003452","host":"s3://npm-registry-packages-npm-production"},"readme":"# Copy anything 🎭\n\n<a href=\"https://www.npmjs.com/package/copy-anything\"><img src=\"https://img.shields.io/npm/v/copy-anything.svg\" alt=\"Total Downloads\"></a>\n<a href=\"https://www.npmjs.com/package/copy-anything\"><img src=\"https://img.shields.io/npm/dw/copy-anything.svg\" alt=\"Latest Stable Version\"></a>\n\n```\nnpm i copy-anything\n```\n\nAn optimised way to copy'ing (cloning) an object or array. A small and simple integration.\n\n## Motivation\n\nI created this package because I tried a lot of similar packages that do copy'ing/cloning. But all had its quirks, and _all of them break things they are not supposed to break_... 😞\n\nI was looking for:\n\n- a simple copy/clone function\n- has to be fast!\n- everything it clones must lose any reference to the original object\n- works with arrays and objects in arrays!\n- supports symbols\n- can copy non-enumerable props as well\n- **does not break special class instances**　‼️\n\nThis last one is crucial! So many libraries use custom classes that create objects with special prototypes, and such objects all break when trying to copy them improperly. So we gotta be careful!\n\ncopy-anything will copy objects and nested properties, but only as long as they're \"plain objects\". As soon as a sub-prop is not a \"plain object\" and has a special prototype, it will copy that instance over \"as is\". ♻️ The flip side is that such an instance stays shared with the original, along with anything nested inside it, so mutating `copy.someDate` is visible on `original.someDate`.\n\nThere is no depth limit — nesting is only bounded by available memory. Circular references are reproduced in the copy instead of being followed forever, and two props pointing at the same object still point at one shared copy afterwards.\n\n## Usage\n\n```js\nimport { copy } from 'copy-anything'\n\nconst original = { name: 'Ditto', type: { water: true } }\nconst copy = copy(original)\n\n// now if we change a nested prop like the type\ncopy.type.water = false\n// or add a new nested prop\ncopy.type.fire = true\n\n// then the original object will still be the same:\noriginal.type.water === true // true\noriginal.type.fire === undefined // true\n```\n\n> Please note, by default copy-anything does not copy non-enumerable props. If you need to copy those, see the instructions further down below.\n\n### Works with arrays\n\nIt will also clone arrays, **as well as objects inside arrays!** 😉\n\n```js\nconst original = [{ name: 'Squirtle' }]\nconst copy = copy(original)\n\n// now if we change a prop in the array\ncopy[0].name = 'Wartortle'\n// or add a new item to the array\ncopy.push({ name: 'Charmander' })\n\n// then the original array will still be the same:\noriginal[0].name === 'Squirtle' // true\noriginal[1] === undefined // true\n```\n\n### Non-enumerable\n\nBy default, copy-anything only copies enumerable properties. If you also want to copy non-enumerable properties you can do so by passing that as an option.\n\n```js\nconst original = { name: 'Bulbasaur' }\n// bulbasaur's ID is non-enumerable\nObject.defineProperty(original, 'id', {\n  value: '001',\n  writable: true,\n  enumerable: false,\n  configurable: true,\n})\nconst copy1 = copy(original)\ncopy1.id === undefined // true\n\nconst copy2 = copy(original, { nonenumerable: true })\ncopy2.id === '001' // true\n```\n\n### Limit to specific props\n\nYou can limit to specific props.\n\n```js\nconst original = { name: 'Flareon', type: ['fire'], id: '136' }\nconst copy = copy(original, { props: ['name'] })\n\ncopy // will look like: `{ name: 'Flareon' }`\n```\n\n> Please note, if the props you have specified are non-enumerable, you will also need to pass `{nonenumerable: true}`.\n\n## Benchmark\n\nRegenerate this section any time with `npm run benchmark`. Every number and every ✅ below comes from actually running the libraries, not from reading their docs.\n\n| clone function      | flat  | mixed  | 1000 objects | 1000 keys | 1000 levels |\n| ------------------- | ----- | ------ | ------------ | --------- | ----------- |\n| **copy-anything**   | 194ns | 693ns  | 94.4µs       | 79.5µs    | 79.1µs      |\n| copy-anything@4.0.5 | 618ns | 1117ns | 176.1µs      | 235.5µs   | 102.3µs     |\n| klona               | 279ns | 300ns  | 43.4µs       | 82.4µs    | 31.2µs      |\n| lodash.cloneDeep    | 391ns | 1202ns | 223.9µs      | 143.8µs   | 177.6µs     |\n| structuredClone     | 787ns | 1935ns | 207.3µs      | 35.4µs    | 223.6µs     |\n\n- **flat** — one object, 10 primitive keys\n- **mixed** — one object 4 levels deep, holding an array of strings and an array of objects\n- **1000 objects** — an array of 1000 flat objects\n- **1000 keys** — one object with 1000 primitive keys, to isolate the cost of enumerating them\n- **1000 levels** — a single-child chain 1000 objects deep\n\n|                                  | copy-anything | copy-anything@4.0.5 | klona | lodash.cloneDeep | structuredClone |\n| -------------------------------- | ------------- | ------------------- | ----- | ---------------- | --------------- |\n| unlimited nesting depth          | ✅            | ❌                  | ❌    | ❌               | ❌              |\n| circular references              | ✅            | ❌                  | ❌    | ✅               | ✅              |\n| shared references stay shared    | ✅            | ❌                  | ❌    | ✅               | ✅              |\n| symbol keys                      | ✅            | ✅                  | ❌    | ✅               | ❌              |\n| non-enumerable props             | ✅            | ✅                  | ❌    | ❌               | ❌              |\n| class instances left alone       | ✅            | ✅                  | ❌    | ❌               | ❌              |\n| clones Date / Map / Set / RegExp | ❌            | ❌                  | ✅    | ✅               | ✅              |\n| survives functions in the input  | ✅            | ✅                  | ✅    | ✅               | ❌              |\n\n_Measured on Apple M3 Pro, Node v24.19.0. Lower is better._\n\n### Why klona is faster in some metrics\n\nklona is the fastest of the bunch and that is not an accident — it is faster **because** it does less. It recurses with a plain `for in` loop and keeps no record of what it has already visited, which is exactly what buys it the speed. Those same two choices are what the ❌ column above is made of.\n\nIf your objects are plain data, shallow, and acyclic, klona is a great pick and you should use it. Here is what changes when they are not.\n\n**Deeply nested data.** Any clone function that recurses is bounded by the JavaScript call stack, so it dies on deep input. copy-anything walks an explicit work list on the heap instead, so it has no such limit.\n\n```js\nlet deep = { value: 'leaf' }\nfor (let i = 0; i < 10000; i++) deep = { nested: deep }\n\nklona(deep) // 💥 RangeError: Maximum call stack size exceeded\ncopy(deep) // ✅ fine — depth is only limited by memory\n```\n\n**Circular references.** A cycle is just infinite depth, so an unvisited-set-free clone follows it until the stack runs out. copy-anything registers each clone before filling it in, so a reference back up the tree resolves to the copy already being built.\n\n```js\nconst user = { name: 'Luca' }\nuser.self = user\n\nklona(user) // 💥 RangeError: Maximum call stack size exceeded\n\nconst copied = copy(user)\ncopied.self === copied // ✅ true — the cycle is reproduced in the copy\ncopied !== user // ✅ true — and it is still a real copy\n```\n\n**Two props pointing at one object.** Without a record of what it has cloned, klona cannot know the two props were the same object, so the copy ends up with two separate ones.\n\n```js\nconst shared = { count: 0 }\nconst original = { a: shared, b: shared }\n\nconst klonad = klona(original)\nklonad.a === klonad.b // ❌ false — silently split into two separate objects\n\nconst copied = copy(original)\ncopied.a === copied.b // ✅ true — still one shared object\ncopied.a !== shared // ✅ true — and detached from the original\n```\n\n**Class instances.** klona rebuilds them with `new x.constructor()`, which throws outright if the constructor requires arguments, and silently skips any prop the constructor sets to the same value. copy-anything copies such instances over as is.\n\n```js\nclass User {\n  constructor(id) {\n    if (id === undefined) throw new Error('id is required')\n    this.id = id\n  }\n}\nconst original = { user: new User(1) }\n\nklona(original) // 💥 Error: id is required\ncopy(original).user === original.user // ✅ true — copied over as is\n```\n\n**Symbols and non-enumerable props.** klona's `for in` loop cannot see either one, so both are dropped from the copy. copy-anything copies symbol keys by default and non-enumerable props with `{ nonenumerable: true }`.\n\nThe trade goes the other way in one place, and it is worth knowing: klona clones `Date`, `Map`, `Set`, `RegExp` and typed arrays, where copy-anything deliberately copies those over as is. If you need those cloned, klona (or `structuredClone`) is the better tool.\n\n## Meet the family (more tiny utils with TS support)\n\n- [is-what 🙉](https://github.com/mesqueeb/is-what)\n- [is-where 🙈](https://github.com/mesqueeb/is-where)\n- [merge-anything 🥡](https://github.com/mesqueeb/merge-anything)\n- [check-anything 👁](https://github.com/mesqueeb/check-anything)\n- [remove-anything ✂️](https://github.com/mesqueeb/remove-anything)\n- [getorset-anything 🐊](https://github.com/mesqueeb/getorset-anything)\n- [map-anything 🗺](https://github.com/mesqueeb/map-anything)\n- [filter-anything ⚔️](https://github.com/mesqueeb/filter-anything)\n- [copy-anything 🎭](https://github.com/mesqueeb/copy-anything)\n- [case-anything 🐫](https://github.com/mesqueeb/case-anything)\n- [flatten-anything 🏏](https://github.com/mesqueeb/flatten-anything)\n- [nestify-anything 🧅](https://github.com/mesqueeb/nestify-anything)\n\n## Source code\n\ncopy-anything has zero dependencies and the whole implementation is one short file you can read in a minute: [src/index.ts](src/index.ts).\n\nIt walks the object with an explicit work list rather than by recursing, which is what lets it handle any nesting depth — a recursive clone throws `RangeError: Maximum call stack size exceeded` somewhere around 2500 levels, and so does every other clone function that recurses, including the browser's own `structuredClone`.\n\nEach clone is registered before it is filled in, so a reference pointing back up the tree resolves to the clone that is already being built instead of being followed forever. That is what makes circular references work.\n","publish_time":1742839055183,"_cnpm_publish_time":1742839055183,"dist-tags":{"latest":"4.1.5"}}