MCPcopy Create free account
hub / github.com/Rich-Harris/magic-string / update

Method update

src/MagicString.ts:754–824  ·  view source on GitHub ↗

* Replaces the characters from `start` to `end` with `content`. The same restrictions as `s.remove()` apply. * * The fourth argument is optional. It can have a storeName property - if true, the original name will be stored * for later inclusion in a sourcemap's names array - and an overwrit

(start: number, end: number, content: string, options?: boolean | UpdateOptions)

Source from the content-addressed store, hash-verified

752 * the content is overwritten, or anything that was appended/prepended to the range as well.
753 */
754 update(start: number, end: number, content: string, options?: boolean | UpdateOptions): this {
755 start = this._resolveIndex(start)
756 end = this._resolveIndex(end)
757
758 if (typeof content !== 'string') {
759 throw new MagicStringError(`content must be a string, got ${typeof content}`)
760 }
761
762 if (start < 0) {
763 throw new MagicStringError(`start ${start} is out of bounds`)
764 }
765 if (end > this.original.length) {
766 throw new MagicStringError(`end ${end} is out of bounds`)
767 }
768 if (start === end) {
769 throw new MagicStringError(
770 `cannot overwrite a zero-length range at ${start}, use appendLeft() or prependRight()`,
771 )
772 }
773 if (start > end) {
774 throw new MagicStringError(`end must be greater than start (start: ${start}, end: ${end})`)
775 }
776
777 this._split(start)
778 this._split(end)
779
780 if (options === true) {
781 if (!warned.storeName) {
782 console.warn(
783 'The final argument to magicString.overwrite(...) should be an options object. See https://github.com/rich-harris/magic-string',
784 )
785 warned.storeName = true
786 }
787
788 options = { storeName: true }
789 }
790 const optionObject = typeof options === 'object' && options ? options : {}
791 const storeName = optionObject.storeName || false
792 const overwrite = optionObject.overwrite || false
793
794 if (storeName)
795 this.storedNames.add(this.original.slice(start, end))
796
797 const first = this.byStart.get(start)! // start < end <= original.length, so _split(start) left a chunk here
798
799 // check the whole range before editing it, so a call that throws
800 // leaves the string as it was
801 for (let chunk = first; chunk.end < end;) {
802 const next = chunk.next
803 if (next === null || next !== this.byStart.get(chunk.end)) {
804 throw new MagicStringError('cannot overwrite across a split point')
805 }
806 chunk = next
807 }
808
809 for (let chunk = first.next; chunk !== null && chunk.start < end; chunk = chunk.next) {
810 // `first` takes the replacement and the rest of the range is emptied.
811 // Unless overwriting, inserts on these chunks are kept as they are on

Callers 1

overwriteMethod · 0.95

Calls 5

_resolveIndexMethod · 0.95
_splitMethod · 0.95
addMethod · 0.45
sliceMethod · 0.45
editMethod · 0.45

Tested by

no test coverage detected